javascript 如何将对象传递给onchange函数?(选择选项)

ajsxfq5m  于 2023-05-12  发布在  Java
关注(0)|答案(2)|浏览(133)

我在一个表中有一个选择下拉列表,当我试图选择一个选项时,我想把整个对象发送给onchange函数。能不能把整个东西都寄出去?我怎样才能做到这一点?
这是我试过的。

data = [
{id:1,name:"tasha",code:"T!@#"},
{id:2,name:"dia",code:"ew34"},
{id:3,name:"alex",code:"loiu"},
{id:4,name:"rubee",code:"1234"},
]

const selectUser = (value: any, record: any) =>{
    console.log("selected user details ", value); //if i select first option it will print {id:1 name:"tasha",code:"T!@#"}
    console.log("table record", record);
  }

const column = [
{
      title: "id",
      dataIndex: "id",
      key: "id",
    },
{
      title: "user",
      dataIndex: "user",
      key: "user",
      render: (text: any, record: any) => {
        return (
          <Select
            style={{ width: 120 }}
            onChange={(user) => selectUser(user, record)}
          >
            {data.map((item: any) => {
              return <Option value={item}>{item.name}</Option>;
            })}
          </Select>
        );
      },
    },
]

我收到以下错误

react-dom.development.js:13414 Uncaught Error: Objects are not valid as a React child (found: object with keys {id, name, code}). If you meant to render a collection of children, use an array instead.

但如果我设置值={item.id},这会很好地工作,不会产生任何错误,但我想发送整个对象,而不仅仅是id

dpiehjr4

dpiehjr41#

不能将对象传递为值。HTML属性被写成字符串/数字。
这是您的声明,但有一个错误:

return <Option value={item}>{item.name}</Option>;

您可以传入索引或id,并在以后使用它来访问数组。还建议为列表元素使用唯一键。

data = [
{id:1,name:"tasha",code:"T!@#"},
{id:2,name:"dia",code:"ew34"},
{id:3,name:"alex",code:"loiu"},
{id:4,name:"rubee",code:"1234"},
]

const selectUser = (value: any, record: any) =>{
    console.log("selected user details ", value[userId]); //if i select first option it will print {id:1 name:"tasha",code:"T!@#"}
    console.log("table record", record);
  }

const column = [
{
      title: "id",
      dataIndex: "id",
      key: "id",
    },
{
      title: "user",
      dataIndex: "user",
      key: "user",
      render: (text: any, record: any) => {
        return (
          <Select
            style={{ width: 120 }}
            onChange={(userId) => selectUser(userId, record)}
          >
            {data.map((item: any) => {
              return <Option value={item.id} key={ite.id}>{item.name}</Option>;
            })}
          </Select>
        );
      },
    },
]

如果你真的想总是传递一个对象,你可以创建你自己的自定义组件来接受一个对象。这显然比上面的要复杂得多。

sqougxex

sqougxex2#

你可以使用JSON.stringify将对象转换为字符串,并将其传递给更改处理程序,然后在更改处理程序中使用JSON.parse将其转换为真实的对象

相关问题