簡體   English   中英

如何為可變對象屬性創建setState的可重用函數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM