【问题标题】:How to reload input value in React / Javascript with Virtual DOM?如何使用 Virtual DOM 在 React / Javascript 中重新加载输入值?
【发布时间】:2014-04-08 21:01:00
【问题描述】:

我在重新加载输入值时遇到问题。

<input type="email" ref="email" id="email" value={this.props.handlingAgent.email}/>

之后我使用

this.props.handlingAgent.email = "asd"

在调试器中this.props.handlingAgent.email 的值实际上是asd,但在输入中仍然是旧值。如何在没有 JQuery 的情况下刷新该值?不应该自动刷新吗?

【问题讨论】:

    标签: javascript dom reactjs


    【解决方案1】:

    首先,道具是传递给您的东西。将它们视为函数参数。孩子真的不应该去修改它们,因为它打破了父母的任何假设并使您的 UI 不一致。

    在这里,由于 prop 已传递给您,您希望从 parent 获取一个处理程序,您可以调用该处理程序来通知您的更改:

    var App = React.createClass({
      getInitialState: function() {
        return {inputValue: ''};
      },
    
      handleChange: function(value) {
        console.log('Value gotten back from the child: ' + value);
        this.setState({
          inputValue: value
        });
      },
    
      render: function() {
        return <Field onChange={this.handleChange} inputValue={this.state.inputValue} />;
      }
    });
    
    var Field = React.createClass({
      handleChange: function(event) {
        // Make sure the parent passes the onChange to you as a prop
        // See what I did here? It's not the actual DOM onChange. We're manually
        // triggering it based on the real onChange fired by the `input`
        this.props.onChange(event.target.value);
      },
    
      render: function() {
        // I named the value prop `inputValue` to avoid confusion. But as you can
        // see from `onChange`, it'd be nicer to name it just `value`
        return <input value={this.props.inputValue} onChange={this.handleChange} />;
      }
    });
    

    所以是的,如果您告诉父母进行更改,它确实会“自动”刷新。您无需修改​​传递给您的内容,而是通过将新值传递给父级来使用普通回调。然后它会将相同的值(或不同的值,如果合适的话)向下刷新给您。

    【讨论】:

    • 当你可以在 onChange 上使用 props.onChange 函数时,你创建一个函数只是为了调用 props.onChange 函数有什么原因吗?像这样:onChange={this.props.onChange}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多