Reactjs 反应:在同一参数上状态和道具

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

我是一名初级开发人员。 我使用了材质ui的Textfield,但我有一个问题。我通过一个属性得到了值,它是有效的!但是,我无法编辑文本字段,因此我希望使用onChange参数,这是我的代码:

<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}