React.js: HTML更新后的子输入默认值是正确的,但在页面上显示不正确

React.js: Child input defaultValue after update is correct in HTML, but not displaying correctly on the page

App 中,我有一个子组件,其中一个子组件包含 <input>,另一个子组件包含 <input>。结构如下:

<App>
  <Parent>
    <ClassWithInput1 />
  </Parent>
  <ClassWithInput2 />
</App>

App.state 中,我有一个字符串 val 可以通过任一 <input> 字段进行设置,并且在两个 defaultValue 中使用 defaultValue 属性显示=14=] 更新时的字段。

当使用 ClassWithInput1 更新时,ClassWithInput2<input> 的值会正确更新。但是,当我在 ClassWithInput2 中更新它时,更改不会反映在 ClassWithInput1 中。 App.state.val 在这两种情况下都被正确更新。我检查了 Chrome 检查器,HTML 中的 value 属性在 ClassWithInput1 中是正确的,但页面上没有显示实际更改。

这是问题的沙盒示例:https://codesandbox.io/s/zen-thunder-z1p81?file=/src/App.js

我该如何解决这个问题?

您可以重构您的输入,使每个输入都有一个本地状态来处理其输入值。在 componentDidUpdate 你检查 this.props.val 是否是一个新值:

Input.js

import React, { Component } from "react";

export default class Input1 extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      inputValue: ''
    };
  }

  handleKeyPress = e => {
    if (e.keyCode === 13) {
      this.inputRef.current.blur();
    }
  };

  handleBlur = e => {
    this.props.setVal(this.state.inputValue);
  };

  componentDidUpdate(prevProp) {
    if (prevProp.val === this.props.val) return
    // it will update input value for other input change
    this.setState({ inputValue: this.props.val })
  }

  render() {
    return (
      <div>
        <input
          spellCheck="false"
          // use value instead of DefaultValue
          value={this.state.inputValue}
          ref={this.inputRef}
          onKeyDown={e => this.handleKeyPress(e)}
          onBlur={e => this.handleBlur(e)}
          // add a onChange handler to update state
          onChange={ e => this.setState({inputValue : e.target.value}) }
        />
      </div>
    );
  }
}