当一个表单元素的值发生变化时,会通过onChange函数更新到组件的state中,则为受控组件
一个表单元素没有value属性(单选按钮和复选框是checked属性),则为非受控组件
受控组件实例
class MyRadio extends React.Component {
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
radioValue: '',
}
}
handleChange(e){
this.setState({
radioValue: e.target.value
})
}
handleSubmit(event){
const {radioValue} = this.state;
alert(radioValue);
event.preventDefault();
}
render() {
const {radioValue} = this.state;
return (
<div>
<form onSubmit={this.handleSubmit}>
<p>gender:</p>
<label>male
<input type="radio" value="male" onChange={this.handleChange} checked={radioValue==='male'}/>
</label>
<label>female
<input type="radio" value="female" onChange={this.handleChange} checked={radioValue==='female'}/>
</label>
<br></br>
<input type="submit" value="提交表单"/>
</form>
</div>
)
}
}
非受控组件实例:
class MyRadio2 extends React.Component {
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
const checkedFlag = this.refs.male.checked === true ? 'male':'female';
alert(checkedFlag);
event.preventDefault();
}
handleChange(e){
const val = e.target.value;
if(val==="male"){
this.refs.female.checked=false;
}
else{
this.refs.male.checked=false;
}
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<p>gender:</p>
<label>male
<input type="radio" value="male" ref="male" onChange={this.handleChange}/>
</label>
<label>female
<input type="radio" value="female" ref="female" onChange={this.handleChange}/>
</label>
<br></br>
<input type="submit" value="提交表单"/>
</form>
</div>
)
}
}