React受控组件和非受控组件

2021-04-12 10:08:57
受控组件就是可以被React state控制的组件 非受控组件可以由ref从DOM节点中获取表单数据 在react中表单组件默认是非受控组件 ```react import React, { Component } from 'react' class NameForm extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.input = React.createRef(); } handleSubmit(event) { alert('A name was submitted: ' + this.input.current.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={this.input} /> </label> <input type="submit" value="Submit" /> </form> ); } } export default NameForm ``` 可以通过初始state中设置表单的默认值,每当表单的值发生变化时,调用onChange事件处理器, 事件处理器通过合成事件对象e拿到改变后的状态,并更新应用的state,setState触发视图的重新渲染,完成表单组件值的更新 ```react import React, { Component } from 'react' class MyInput extends Component{ handleContentChange = (e)=>{ this.setState({ content: e.target.value }) } render(){ return( <div> <input type="text" value={this.state.value} onChange={this.handleContentChange} /> </div> ) } } export default MyInput ```