【问题标题】:Handling multiple textfield with single onChange react hooks使用单个 onChange 反应钩子处理多个文本字段
【发布时间】:2020-08-27 11:54:13
【问题描述】:

我在管理对某些文本字段的控件时遇到了一些问题。 我有一个对象

let obj = {
  [
   {
    name:"a",
    adress:[{"foo":a1,"bar":a1}],
    comment:"aaaaa"
   },
   {
    name:"b",
    adress:[{"foo":b1,"bar":b1}],
    comment:"bbbbb"
   }
  ]
}

我生成动态文本字段

{obj.map((item, i) => {
 return <TextField name = {item.name} value={item.comment} onChange={(e)=>{handleComment(e,item.name)}}/>
})}

我想根据每个特定文本字段的名称修改 comment

const handleComment = (e,name) =>{
  e.preventDefault();
  setObject({...obj,comment:e.target.value})
}

我无法以正确的方式做到这一点。我不知道该怎么做。如果你们能帮助我,那就太棒了。谢谢!

【问题讨论】:

  • 好的,那么问题是什么?我看到的只是一堆代码。
  • 我无法以正确的方式做到这一点。我不知道该怎么做。谢谢
  • 您需要使用 useState() 管理状态下的 obj。然后根据输入更新状态
  • 如果您可以创建小型沙盒演示,我可以为您提供相同的帮助..

标签: reactjs material-ui react-hooks


【解决方案1】:

Ciao,你可以在handleComment 函数中使用一个数组来复制当前状态。然后更新该数组并设置状态。 假设你有:

const obj = [
    {
      name: "a",
      adress: [{ foo: "a1", bar: "a1" }],
      comment: ""
    },
    {
      name: "b",
      adress: [{ foo: "b1", bar: "b1" }],
      comment: ""
    }
  ];
  const [object, setObject] = useState(obj);

return 喜欢:

return object.map((item, i) => {
    return (
      <TextField
        name={item.name}
        value={item.comment}
        onChange={(e) => {
          handleComment(e, item); 
        }}
      />
    );
  });

那么你的handleComment就变成了:

const handleComment = (e, item) => {
    e.preventDefault();
    let result = object;   // copy state
    result = result.map((el) => {  // map array to replace the old comment with the new one
      if (el.name === item.name) el.comment = e.target.value;
      return el;
    });
    setObject(result); // set state with new comment
  };

Here 一个代码框示例。

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多