React js,如何在输入更改时更新状态对象值?

16 浏览
0 Comments

React js,如何在输入更改时更新状态对象值?

此问题已经有了答案

如何在React中更新嵌套状态属性

在React JS中,我正在尝试创建一个函数,在输入字段的onChange事件中使用输入的值更新状态。

状态模型必须保持这样,因为我必须像这样发布它(以匹配API结构等)。

但是我不知道如何获得每个记录的“答案”部分的状态。

// State --------------------------------------
state = {
    values: [
      //1
      {
        section: "a",
        answers:
        {
            1a: 1,
            1b: 2,
            1c: 3,
            1d: 4,
            1e: 5
        }   
      },
      //2
      {
        section: "b",
        answers:
        {
            2a: 1,
            2b: 2,
            2c: 3,
            2d: 4,
            2e: 5,
            2f: 6,
            2g: 7,
            2h: 7
        }   
      }
   ]
}
// Set value ----------------------------------
  setValue = (key, val) => {
    this.setState((state) => ({ 
      values: {
        ...state.values,
        [key]: val
      }
    }));
  };
// Handle input change ------------------------
  handleChange = key => e => {
    this.setValue(key, e.target.value)
  };
//Usage ---------------------------------------


admin 更改状态以发布 2023年5月21日
0
0 Comments

你可以尝试下面的代码:

以下是代码:

// Example class component
class Thingy extends React.Component {
   constructor(props) {
   super(props)
   this.state = {
       values: [
      //1
      {
        section: "a",
        answers:
        {
            a1:1,
            b1:2,
            c1:3,
            d1:4,
            e1:5
        }   
      },
      //2
      {
        section: "b",
        answers:
        {
            a2:1,
            b2:2,
            c2:3,
            d2:4,
            e2:5,
            f2:6,
            g2:7,
            h2:7
        }   
      }
   ]
    }
  }
  setValue = (Key, val) => {
    let output = this.state.values.map(value=>{
       if (Key in value.answers) 
       {
          let tempValue = {
              ...value,
              answers:
              {
                 ...value.answers,
                 [Key] : Number(val)
              }
          }
          return tempValue
       }
       else
       {
          return value
       }
    })
    this.setState({
       values:output
    })
  }; 
  handleChange =(e, key) => {
    this.setValue(key, e.target.value)
  }
  getDefaultValue=(Key)=>{
    let output
    this.state.values.forEach(value=>{
       if (Key in value.answers) 
       {
          output = value.answers[Key]
       }
    })
    return output
  }
  render() {
    return (
         this.handleChange(e,"a1")} value={this.getDefaultValue("a1")} />
         this.handleChange(e,"c2")} value={this.getDefaultValue("c2")} /> 
    )
  }
}
// Render it
ReactDOM.render(
  ,
  document.getElementById("react")
);




0