【问题标题】:React.js: Child input defaultValue after update is correct in HTML, but not displaying correctly on the pageReact.js:更新后的子输入defaultValue在HTML中是正确的,但在页面上显示不正确
【发布时间】:2020-10-04 09:26:16
【问题描述】:

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

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

App.state 中,我有一个字符串val,可以通过任一&lt;input&gt; 字段设置,并在更新时在两个&lt;input&gt; 字段中使用defaultValue 属性显示。

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

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

我该如何解决这个问题?

【问题讨论】:

    标签: javascript html reactjs react-component


    【解决方案1】:

    您可以将输入重构为每个都有一个本地状态来处理其输入值。在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>
        );
      }
    }
    

    【讨论】:

    • 谢谢!为什么直接将其设置为this.props.val 不起作用?
    • 因为defaultValue 只是输入时没有变化的初始值。同样,如果您将this.props.val 直接设置为value,它将阻止输入更改为空字符串(即 props.val 初始值)。您需要一个状态和一个 onChange 处理程序才能正常工作。
    • 感谢您的详尽回答!
    猜你喜欢
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 2011-11-28
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多