react 表单

受控组件:

import React from 'react'; class CommentBox extends React.Component{ constructor(props){ super(props) this.state = { value: '' } this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } handleChange(event){ console.log(event.target.value) this.setState({ value: event.target.value }) } handleSubmit(event){ console.log(this.state.value) event.preventDefault(); //阻止默认事件 } render() { return( <form className="p-5" onSubmit={this.handleSubmit}> <div className="form-group"> <label>留言:</label> <input type="text" className="form-control" value={this.state.value} onChange={this.handleChange}> </input> </div> <button type="submit" className="btn btn-primary">提交</button> </form> ) } } export default CommentBox
非受控组件:

import React from 'react'; class CommentBox extends React.Component{ constructor(props){ super(props) this.submitHandle = this.submitHandle.bind(this) } submitHandle(event){ console.log(this.textInput.value); event.preventDefault(); } render() { return( <form className="p-5" onSubmit={this.submitHandle}> <div className="form-group"> <label>留言:</label> <input ref={ (textInput) => {this.textInput = textInput}} type="text" className="form-control" > </input> </div> <button type="submit" className="btn btn-primary">提交</button> </form> ) } } export default CommentBox

 

posted @ 2020-10-31 10:29  氧化成风  阅读(62)  评论(0编辑  收藏  举报