React:状态和道具在同一个参数上

React : State and props on the same parameter

我是一名初级开发人员。 我使用 material ui 的文本字段,但我遇到了问题。我通过 属性 获得值,它有效!但是我无法编辑文本字段,所以我想使用 onChange 参数,这是我的代码:

<TextField ref="docLibelle" value={this.props.lastuploadfile.content}  onChange={this._handleTextFieldChange}

我的功能:

_handleTextFieldChange = (e:any) => {
    this.setState({
        showReferenceIsRequired : false,
        libelDoc: e.target.value
    });
}

然后我尝试这样做:

<TextField ref="docLibelle" value={this.state.libelDoc&& this.props.lastuploadfile.content}  onChange={this._handleTextFieldChange}

但它不起作用..我如何通过 属性 获取值并编辑文本字段?

感谢您的回答!

问题是,在值 属性 中,您使用的是 props 值,并且在 onChange 方法中更新了 state 值,因此您的 textfield只读

解决方案

1. 从父组件传递 function 并且 textfieldonChange 使用 function 更新父组件值,它会像这样工作:

在子组件中:

<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的初始值存入state变量:

constructor(props){
   super(props);
   this.state = {libelDoc: props.lastuploadfile.content}
}

value 属性 中使用 textfield 中的变量:

<TextField ref="docLibelle" value={this.state.libelDoc}  onChange={this._handleTextFieldChange}

更新 onChange 方法中的 state 变量:

_handleTextFieldChange = (event, value) => {
     this.setState({
         showReferenceIsRequired : false,
         libelDoc: value
     });        
 }

我认为解决方案非常简单。由于您希望能够更改 textField 值并使用一个值对其进行初始化,因此您可以在 componentDidMount 方法

中使用 props 设置状态
componentDidMount(){
    this.setState({libelDoc: this.props.lastuploadfile.content})
} 

并像'

一样使用它
<TextField ref="docLibelle" value={this.state.libelDoc}  onChange={this._handleTextFieldChange}