gpt4 book ai didi

javascript - 通过更新 Prop 更新输入值

转载 作者:行者123 更新时间:2023-11-30 09:47:52 26 4
gpt4 key购买 nike

我有一个输入值,但在单击“重置”链接后无法更新

class DiscountEditor extends Component {
render() {
<div className="inline field">
<a className="ui reset" onClick={this.props.onReset}>Reset</a>

<input
value={this.props.discount}
onChange={this.props.onDiscountChanged}>
</input>
</div>
}
}

class SalesLine extends Component {
onReset(lineItem) {
this._discount = 0;
this.forceUpdate();
}

render() {
<DiscountEditor
value={this._discount}
onChange={this.props.onDiscountChanged}
onReset={this.onReset.bind(this)}
</DiscountEditor>
}
}

当我单击重置按钮时,DiscountEditor 组件将再次呈现,并且 this.props.discount 具有正确的值,即零,但输入值将保持不变,不会更新为零。为什么呢?

最佳答案

您调用 Prop value 但您使用的是 this.props.discount。如果你把它改成

<input
value={this.props.value}
onChange={this.props.onDiscountChanged}>
</input>

它应该可以工作。

您还应该将 discount 放入您的 SalesLine 组件中,而不是手动调用 forceUpdate

class SalesLine extends Component {
constructor(props) {
super(props);
this.state = {discount: 0};
}

onReset(lineItem) {
this.setState({discount: 0});
}

render() {
return <DiscountEditor
value={this.state.discount}
onChange={this.props.onDiscountChanged}
onReset={this.onReset.bind(this)}
</DiscountEditor>;
}
}

关于javascript - 通过更新 Prop 更新输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38054388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com