为什么我的输入值不能用React更新?

Dav*_*ein 3 javascript reactjs

我的组件中有以下代码.当我更新某些东西时它会被调用,从而取代UI中的一堆东西.一切都在更新,除了用户看到的输入值.

let input = {
  id: 'discount-' + geo + '-' + segment,
  value: percentage,
  disabled: applyToAll,
  placeholder: '0.00'
};

cells.push(
  <td key={'cell-' + geo + '-' + segment} className="discount-segment cfix">
    <Text {...input} />
  </td>
);
Run Code Online (Sandbox Code Playgroud)

这是<Text>返回,用的东西为清楚起见移除

return (
  <div className={containerClasses.join(' ')} id={'field-container-' + id}>
    {label}
    <input
      autoComplete="off"
      type="text"
      id={id}
      ref="input"
      {...extraProps}
      name={id}
      className={classes.join(' ')}
      defaultValue={this.props.value}
      onChange={this.props.onChange}
      />
  </div>
);
Run Code Online (Sandbox Code Playgroud)

一切都很好.假设percentage5在开始时,它将5在字段中显示.然后我做了一些更新percentage到50的事情.(控制台日志将在重新渲染时显示正确的数字).但是,该值仅5在UI中显示.我defaultValue在输入字段上使用,但我认为应该改变,因为整个事物从父级重新渲染.

编辑已 更新<Text>以设置value而不是defaultValue.但是state,当用户输入时,我需要使用更新值.然后当我重新渲染时,我会发送具有适当值的新道具,但当然道具不会更新.Catch-22对我来说.

dco*_*eau 12

您需要执行以下几个步骤:

  1. 您的输入需要使用valueonChange道具,不要使用defaultValue
  2. 使用props初始化您的状态以设置默认值
  3. 当你的道具改变时更新你的状态

所以,例如:

const MyComponent = React.createClass({

  propTypes: {
    defaultInputValue: React.PropTypes.string
  },

  getInitialState() {
    return {
      inputValue: this.props.defaultInputValue
    };
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.defaultInputValue !== this.props.inputValue) {
      //Forcibly overwrite input value to new default if the default ever changes
      this.setState({inputValue: nextProps.defaultInputValue});
    }
  },

  render() {
    return <input type="text"
                  value={this.state.inputValue}
                  onChange={e => this.setState({inputValue: e.target.value})} />;
  }
});
Run Code Online (Sandbox Code Playgroud)

一般来说,道具的初始化状态是禁忌.如果我在代码审查中看到这种情况,我可能会有点畏缩,因为可能有一些行为可以简化.

你也可以这样做:

<input value={this.state.inputValue || this.props.defaultInputValue} />
Run Code Online (Sandbox Code Playgroud)

如果您清除了输入,则输入值将恢复为prop值.在这种情况下,您不必使用新道具强制覆盖状态.