javascript - 如何使用虚拟 DOM 在 React/Javascript 中重新加载输入值?

标签 javascript dom reactjs

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

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

然后我用

this.props.handlingAgent.email = "asd"

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

最佳答案

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

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

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} />;
  }
});

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

关于javascript - 如何使用虚拟 DOM 在 React/Javascript 中重新加载输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22220873/

相关文章:

javascript - 一遍又一遍地调用功能

javascript - 是否可以在 React 组件的功能表示中包含静态属性?

reactjs - typescript 给我一个错误 : Expected 0 arguments, 但得到 1

JavaScript重复 Action

Javascript Windows.Location 传递复杂的 JSON 对象

javascript - 导出对象中的对象

node.js - 使用 "create-react-app my-app"创建 React 应用程序时出错

javascript 未运行。 Firebug 说 "reload the page to get source for: ..."

javascript - React.js 未捕获错误 : _registerComponent(. ..):目标容器不是 DOM 元素

javascript - 为什么当变量为 true 时 JavaScript 最后执行 DOM 语句?