我在重新加载输入值时遇到问题。
<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/