![](/img/trans.png)
[英]How can I make an object property be both a function and a variable in Javascript?
[英]How can I create a reusable function that will setState for a variable object property?
我有一個onChange函數來更新所有表單輸入的狀態。 我在這里嘗試更新的狀態是作為對象嵌套在數組中,但我不確定如何創建一個可重用的函數,它將根據更改的表單輸入更新特定的對象屬性。
這是我的功能:
onChangeHandler = (e, index) => {
let currentStateObject = [...this.state.fundGroups]; //copying the current state
// This works, but I don't want allocationName to be hardcoded.
// How can I pass in a variable that relates to the specific property
// based on which input field is changed?
currentStateObject[index].allocationName = e.target.value;
this.setState({
currentStateObject
});
}
這是我嘗試過但它不起作用並使用無效的令牌消息中斷我的代碼:
currentStateObject[index].[e.target.name] = e.target.
我試過這個,因為在我的輸入字段中,我添加了name="allocationName"
有誰知道我是否接近解決這個問題? 我對React很新。 謝謝。
你幾乎得到了它。 簡單地刪除.
在[index]
和[e.target.name]
如:
currentStateObject[index][e.target.name] = e.target.value;
你可以簡單地說:
onChangeHandler(event) {
this.setState({ [event.target.name]: event.target.value })
}
這是一些狀態操作的例子
state = {
random: [],
counter: 1
}
stateHandler = (e)=>{
let oldrandom = [...this.state.random]
oldrandom[e.target.name] = e.target.value;
this.setState({random:oldrandom })
}
manipulate state with a functional approach
stateHandler = ()=>{
this.setState((state,props)=>{
counter: state.counter+props.increment
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.