gpt4 book ai didi

javascript - 当 React 中的代码更改其值时如何在输入上触发 onChange 事件?

转载 作者:行者123 更新时间:2023-11-29 20:29:16 25 4
gpt4 key购买 nike

我正在尝试学习 React JS,并且正在从事个人项目。我被卡住了,因为我无法将子组件中输入字段的值传递给父组件的状态。

我曾尝试使用 onChange 事件,但由于某种原因,它正在调用的函数 handleChange 没有被触发。

这是父组件的一个片段:

class App extends Component {
state = {
myArray: [{ //myArray is being updated by another child component, which sets the values for id and amount; this works fine
id: 1,
amount: 12
},
{
id: 2,
amount: 23
}
]
total: 0 //expected value for total is 35
};

handleChange = e => {
const { name, value } = e.target
this.setState({
[name]: value
});
}

render() {
return (
<Child
handleChange={this.handleChange}
myArray={this.state.myArray} />
)
}
}

这是子组件的一个片段:

class Child extends Component {

render() {
const { myArray, handleChange } = this.props;

const totalAmount = myArray.reduce(function (a, b) {
return a + b.amount;
}, 0);

return (
<div>
<label htmlFor="total"> Total Amount: </label>
<input id="total"
name="total"
type="number"
placeholder="0.00"
value={totalAmount}
onChange={e => handleChange(e)}
/>
</div>
)
}
}

总计输入字段中的值正确呈现。但是,我想要实现的是每次更改此输入字段值时(当其他子组件更新 myArray 值,因此总和也会更改时),我希望更新父组件状态下的总值。

最佳答案

您正在立即执行 callback 而不是传递 event 对象。像这样尝试

onChange = {e => handleChange("total")(e)}

同样在 handleChange 中你的参数名称是错误的

handleChange = propertyName => e => {
this.setState({
[property]: e.target.value
});
}

应该是

handleChange = property => e => {
this.setState({
[property]: e.target.value
});
}

关于javascript - 当 React 中的代码更改其值时如何在输入上触发 onChange 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58711126/

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