Reactjs 反应:在同一参数上状态和道具
我是一名初级开发人员。 我使用了材质ui的Textfield,但我有一个问题。我通过一个属性得到了值,它是有效的!但是,我无法编辑文本字段,因此我希望使用onChange参数,这是我的代码:Reactjs 反应:在同一参数上状态和道具,reactjs,material-ui,Reactjs,Material Ui,我是一名初级开发人员。 我使用了材质ui的Textfield,但我有一个问题。我通过一个属性得到了值,它是有效的!但是,我无法编辑文本字段,因此我希望使用onChange参数,这是我的代码: <TextField ref="docLibelle" value={this.props.lastuploadfile.content} onChange={this._handleTextFieldChange} 我试着: <TextField ref="docLibelle" valu
<TextField ref="docLibelle" value={this.props.lastuploadfile.content} onChange={this._handleTextFieldChange}
我试着:
<TextField ref="docLibelle" value={this.state.libelDoc&& this.props.lastuploadfile.content} onChange={this._handleTextFieldChange}
问题是,在value属性中,您正在使用props
值,并且在onChange
方法中更新状态
值,因为您的文本字段
为只读
解决方案:
1.从父组件传递一个函数
,并一旦更改文本字段
使用该函数
更新父值,它将工作,如下所示:
在子组件中:
<TextField ref="docLibelle" value={this.props.lastuploadfile.content} onChange={this._handleTextFieldChange}/>
_handleTextFieldChange = (e:any) => {
this.setState({
showReferenceIsRequired : false,
});
this.props.updateValue(e.target.value);
}
updateValue(value){
let = this.state.lastuploadfile;
lastuploadfile.content = value;
this.setState({lastuploadfile})
}
2.将props
值存储在state
变量中,并在textfield的value属性中使用该变量
将textfield
的初始值存储在state
变量中:
constructor(props){
super(props);
this.state = {libelDoc: props.lastuploadfile.content}
}
在textfield
的value
属性中使用该变量:
<TextField ref="docLibelle" value={this.state.libelDoc} onChange={this._handleTextFieldChange}
我认为解决办法很简单。由于您希望能够更改textField
值并使用值对其进行初始化,因此只需在componentDidMount方法中使用props设置state即可
componentDidMount(){
this.setState({libelDoc: this.props.lastuploadfile.content})
}
用它就像
<TextField ref="docLibelle" value={this.state.libelDoc} onChange={this._handleTextFieldChange}
{this.state.libelDoc&&this.props.lastuploadfile.content}这将返回true或false。那么,什么不起作用?很好!谢谢你的回答,很有效!这很简单,但我不去想,谢谢:)谢谢你的回答!
componentDidMount(){
this.setState({libelDoc: this.props.lastuploadfile.content})
}
<TextField ref="docLibelle" value={this.state.libelDoc} onChange={this._handleTextFieldChange}