Controlled Components
Uncontrolled Components
Controlled Component
将React组件的state
与表单的状态绑定,使state
成为表单状态值的“唯一可信来源”,只能通过组件的setState()
方法修改,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } }
|
Uncontrolled Components
与Controlled Component不同,Uncontrolled Component使用ref属性,获取原生DOM引用,再操作DOM上的值。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class NameForm extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { alert('A name was submitted: ' + this.input.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={(input) => this.input = input} /> </label> <input type="submit" value="Submit" /> </form> ); } }
|
默认值
React组件中,设置表单value
属性值会覆盖DOM的value
值(无法更改,除非用Controlled Components修改绑定的state
),因此不能使用value
属性,需使用defaultValue
属性,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input defaultValue="Bob" type="text" ref={(input) => this.input = input} /> </label> <input type="submit" value="Submit" /> </form> ); }
|
checkbox和radio使用defaultChecked
,select使用defaultValue
。