![](/img/trans.png)
[英]Getting a navbar to work in React. Sending a function to a child through props?
[英]Optimize the function in React. Having setState key as a props?
擁有這個功能,它基本上定義了要收聽的表單輸入。 然而,隨着輸入的增長,函數也在增長。
我正在考慮傳遞一個 id 並將其與狀態鍵的值進行比較,這樣這個狀態就會改變。
onChange = event => {
if (event.target.id === "Name") {
this.setState({
name: event.target.value
});
} else if (event.target.id === "Position") {
this.setState({
position: event.target.value
});
} else if (event.target.id === "Text") {
this.setState({
text: event.target.value
});
}
};
那么如何正確處理狀態呢?
我在想這樣的事情。 因此輸入表單調用具有 id 值的函數並找到具有相同名稱|值的狀態。
onChange = (event, id) => {
this.setState({
{ id value as a key?}: event.target.value
})
}
但是,不明白如何正確編寫它。 請問有什么幫助嗎?
你可以這樣做
onChange = event => {
this.setState({
[event.target.id]: event.target.value
})
}
還將您的元素 id 更改為name
、 position
和text
您更有可能應該使用useReducer
。
useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.