非受控组件
1 .类似于传统的HTML表单输入,如果想要获取输入的值,从ref获取他们
class Form extends Component {
handleSubmitClick = () => {
const name = this._name.value;
}
render() {
return (
<div>
<input type="text" ref={input =>this._name = input}
defaultValue="默认值"
/>
<button onClick={this.handleSubmitClick}>Sign up</button>
</div>
);
}
}
受控表单
1 .接受当前值作为属性,或者作为改变值得时候调用
class Form extends Component {
constructor() {
super();
this.state = {
name: '',
};
}
handleNameChange = (event) => {
this.setState({ name: event.target.value });
};
render() {
return (
<div>
<input
type="text"
value={this.state.name}
onChange={this.handleNameChange}
/>
</div>
);
}
}
2 . .非受控组件将真实数据存储在DOM节点中。使用非受控组件得时候,更加容易集成React和非React代码
网友评论