Swe*_*ety 9 reactjs material-ui
我在下面收到此错误.
警告:TextField正在更改要控制的文本类型的不受控制的输入.输入元素不应从不受控制切换到受控制(或反之亦然).决定在组件的使用寿命期间使用受控或不受控制的输入元素.
我正在使用材料-ui.
这是我的代码:
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我哪里错了?
May*_*kla 15
原因是,您没有定义phonein state变量,因此在初始渲染时TextField将被视为不受控制的组件,因为value属性将具有undefined值.
在这一行
value = {this.state.phone} => this.state.phone最初是未定义的
要在状态变量中修复此定义手机,如下所示:
constructor(props) {
super(props)
this.state = {
errorText: '',
value:this.props,
phone: ''
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用如下的短路评估来定义value属性:
value = {this.state.phone || ''} //(undefined || '') = ''
Run Code Online (Sandbox Code Playgroud)
Ash*_*shh 10
因为您的价值未定义,这就是您收到此错误的原因
尝试这个
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>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5009 次 |
| 最近记录: |