【问题标题】:React update input text value using state and make it mutable使用状态响应更新输入文本值并使其可变
【发布时间】:2017-05-19 15:49:41
【问题描述】:

我想使用 state 和 React value 属性更改输入文本值,并使该字段可编辑。

我的组件的构造函数:

constructor(props) {
    super(props);

    // States
    this.state = {
        value: this.props.object.subtext
    };

    this._handleChange = this._handleChange.bind(this);
}

我的render() 功能:

return (
    <input
        type={this.props.object.type}
        value={this.props.object.subtext}
        onChange={this._handleChange}
    />
);

componentDidUpdate()函数:

componentDidUpdate() {
    if (this.state.value !== this.props.object.subtext) {
        this.setState({value: this.props.object.subtext});
    }
}

对于_handleChange(e) 函数:

_handleChange(e) {
    this.props.object.subtext = e.target.value;
    this.componentDidUpdate(); // not sure it's right or not
}

代码运行良好,但我有点不确定这是不是最佳实践,因为我在事件处理函数中手动调用了this.componentDidUpdate()

我这样做是为了修复我之前的错误,即当状态改变时输入组件的值不会被更新。

我想知道我所做的是否正确,任何 cmets 或答案将不胜感激。

【问题讨论】:

  • 不要更改组件内部的道具。 _handleChange 应该将值传递给父组件回调

标签: javascript reactjs typescript


【解决方案1】:

不,自己调用生命周期函数不是一个好习惯

除此之外,您可以修改您的状态道具,例如

constructor(props) {
    super(props);

    // States
    this.state = {
        value: this.props.object.subtext
    };

    this._handleChange = this._handleChange.bind(this);
}
componentWillReceiveProps(nextProps) {
    if (this.props.object.subtext !== nextProps.object.subtext) {
        this.setState({value: nextProps.object.subtext});
    }
}
_handleChange(e) {

    //cal a parent compoent function
    this.props.changeProps(e.target.value);
}

【讨论】:

  • this.props.changeProps() 来自哪里?
  • 在父组件中定义一个函数 changeProps 来改变传递给子元素的值 object.subtext 并将这个函数传递给你的子函数,例如 {this.changeProps (val)}} />
  • 但是,输入组件现在变得不可变了。
  • 这是正确的做法,this.props.object.subtext = e.target.value;,是错误的,
  • this.props.object.subtext = e.target.value; 是否让它变得不可变?
【解决方案2】:

正如您所怀疑的那样,致电componentDidUpdate 是个坏主意。您可以在_handleChange 中更改您的状态并删除componentDidUpdate 调用。

【讨论】:

    【解决方案3】:

    您可以在_handleChangesetState。但是,您需要为您当地的州绑定到this.state.value,而不是this.props.object.subtext。请注意以下...

    constructor(props) {
      super(props);
    
      this.state = {
        value: this.props.object.subtext
      };
    }
    
    _handleChange(e) {
      this.setState({
        value: e.target.value
      });
    }
    
    render() {
      return (
        <input
          type={this.props.object.type}
          value={this.state.value}
          onChange={this._handleChange.bind(this)}
        />
      );
    }
    

    或者,如果您正在寻找没有本地状态的仅props 解决方案,我建议您提供redux 看看。

    【讨论】:

    • 我试过了,但是状态改变时输入的文本值没有更新。
    • 应该可以正常工作。当然,虽然不是 TypeScript 或类,但这是一个完全复制的工作示例 - JSFiddle example
    猜你喜欢
    • 1970-01-01
    • 2016-04-01
    • 2021-09-27
    • 1970-01-01
    • 2016-11-10
    • 2019-01-10
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多