ReactJS警告:TextField正在更改要控制的文本类型的非受控输入
我在下面得到了这个错误 警告:TextField正在更改要控制的文本类型的非受控输入。输入元件不应从非受控切换到受控(反之亦然)。在组件的使用寿命内,决定使用受控或非受控输入元件 我使用的是材料界面 这是我的密码:ReactJS警告:TextField正在更改要控制的文本类型的非受控输入,reactjs,material-ui,Reactjs,Material Ui,我在下面得到了这个错误 警告:TextField正在更改要控制的文本类型的非受控输入。输入元件不应从非受控切换到受控(反之亦然)。在组件的使用寿命内,决定使用受控或非受控输入元件 我使用的是材料界面 这是我的密码: class RegistrationForm extends React.Component{ constructor(props) { super(props) this.state = { errorText: '', value:this.props } }
class RegistrationForm extends React.Component{
constructor(props) {
super(props)
this.state = { errorText: '', value:this.props }
}
phone(event) {
var strRegExpMobile=/^\d{10}$/;
if (event.target.value.match(strRegExpMobile)) {
this.setState({ errorText: '',
phone:event.target.value
})
} else {
this.setState({ errorText: 'Invalid format' })
}
}
handleSubmit(event){
alert("submit");
var data={
phone:this.state.phone
}
console.log(data)
}
render() {
return (
<div>
<TextField hintText="Phone"
floatingLabelText="Phone"
name="phone"
value={this.state.phone}
errorText= {this.state.errorText}
onChange={this.phone.bind(this)}/>
<RaisedButton label="Submit"
primary={true}
onClick={this.handleSubmit.bind(this)}/>
</div>
)
}
}
类注册表单扩展了React.Component{
建造师(道具){
超级(道具)
this.state={errorText:'',值:this.props}
}
电话(活动){
var strRegExpMobile=/^\d{10}$/;
if(event.target.value.match(strRegExpMobile)){
此.setState({errorText:''),
电话:event.target.value
})
}否则{
this.setState({errorText:'无效格式'})
}
}
handleSubmit(事件){
警报(“提交”);
var数据={
电话:这个。州。电话
}
console.log(数据)
}
render(){
返回(
)
}
}
谁能说出我错在哪里 原因是,您没有在
状态
变量中定义电话
,因此初始呈现文本字段将被视为非受控组件,因为value属性将具有未定义的
值
在这一行
value={this.state.phone}
=>this.state.phone最初未定义
要修复此define phone in state变量,请执行以下操作:
constructor(props) {
super(props)
this.state = {
errorText: '',
value:this.props,
phone: ''
}
}
value = {this.state.phone || ''} //(undefined || '') = ''
或使用以下命令定义值属性:
constructor(props) {
super(props)
this.state = {
errorText: '',
value:this.props,
phone: ''
}
}
value = {this.state.phone || ''} //(undefined || '') = ''
因为您的值未定义,所以会出现此错误 试试这个
render() {
return (
<div>
<TextField hintText="Phone"
floatingLabelText="Phone"
name="phone"
value={this.state.phone || ''}
errorText= {this.state.errorText}
onChange={this.phone.bind(this)}/>
<RaisedButton label="Submit"
primary={true}
onClick={this.handleSubmit.bind(this)}/>
</div>
)
}
render(){
返回(
)
}
一旦您在onChange函数中设置state,它将接受该值,该值将在TextField中填充。@Sweety如果您无法更改文本,请查看您是否输入了regex在手机函数中提到的有效文本格式,或者查看控制台中是否有任何错误。否则,这个答案就足够了。请检查一下——另一个解决方案是使用defaultValue属性,而不是value属性。根本原因在这个链接中得到了很好的解释-引用Twisty的注释-如果您最初将undefined或null作为value prop传递,那么组件将作为一个“非受控”组件开始使用。一旦您与组件交互,我们将设置一个值并将其更改为“受控”组件,并发出警告。