警告:组件正在更改要控制的文本类型的非受控输入。输入元件不应从非受控切换到受控(反之亦然)。决定在部件的使用寿命内使用受控或非受控输入元件*
以下是我的代码:
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>
)
}
如上所述,您需要设置初始状态,在我的例子中,我忘记在setSate()中添加“”引号;
const AddUser = (props) => {
const [enteredUsername, setEnteredUsername] = useState()
const [enteredAge, setEnteredAge] = useState()
出现以下错误
正确的代码是简单地将初始状态设置为空字符串“”
const AddUser = (props) => {
const [enteredUsername, setEnteredUsername] = useState('')
const [enteredAge, setEnteredAge] = useState('')
如果在字段中使用多个输入,请执行以下操作:例如:
class AddUser extends React.Component {
constructor(props){
super(props);
this.state = {
fields: { UserName: '', Password: '' }
};
}
onChangeField = event => {
let name = event.target.name;
let value = event.target.value;
this.setState(prevState => {
prevState.fields[name] = value;
return {
fields: prevState.fields
};
});
};
render() {
const { UserName, Password } = this.state.fields;
return (
<form>
<div>
<label htmlFor="UserName">UserName</label>
<input type="text"
id='UserName'
name='UserName'
value={UserName}
onChange={this.onChangeField}/>
</div>
<div>
<label htmlFor="Password">Password</label>
<input type="password"
id='Password'
name='Password'
value={Password}
onChange={this.onChangeField}/>
</div>
</form>
);
}
}
在以下位置搜索您的问题:
onChangeField = event => {
let name = event.target.name;
let value = event.target.value;
this.setState(prevState => {
prevState.fields[name] = value;
return {
fields: prevState.fields
};
});
};