警告:组件正在更改要控制的文本类型的非受控输入。输入元件不应从非受控切换到受控(反之亦然)。决定在部件的使用寿命内使用受控或非受控输入元件*
以下是我的代码:
constructor(props) {
super(props);
this.state = {
fields: {},
errors: {}
}
this.onSubmit = this.onSubmit.bind(this);
}
....
onChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
....
render() {
return(
<div className="form-group">
<input
value={this.state.fields["name"]}
onChange={this.onChange.bind(this, "name")}
className="form-control"
type="text"
refs="name"
placeholder="Name *"
/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
)
}
首先设置当前状态。。。此状态
这是因为当您要分配一个新状态时,它可能是未定义的。因此,它也将通过设置状态提取当前状态来固定
this.setState({...this.state, field})
如果您的状态中有一个对象,则应按如下方式设置状态:,假设您必须在用户对象内设置用户名。
this.setState({user:{...this.state.user, ['username']: username}})
可以应用多种方法:
基于类的方法:使用本地状态并使用默认值定义现有字段:
constructor(props) {
super(props);
this.state = {
value:''
}
}
<input type='text'
name='firstName'
value={this.state.value}
className="col-12"
onChange={this.onChange}
placeholder='Enter First name' />
在功能型组件中使用Hooks React>16.8:
[value, setValue] = useState('');
<input type='text'
name='firstName'
value={value}
className="col-12"
onChange={this.onChange}
placeholder='Enter First name' />
如果使用propTypes并在HOC组件为函数样式的情况下为propTypes提供默认值。
HOC.propTypes = {
value : PropTypes.string
}
HOC.efaultProps = {
value: ''
}
function HOC (){
return (<input type='text'
name='firstName'
value={this.props.value}
className="col-12"
onChange={this.onChange}
placeholder='Enter First name' />)
}