0

我在表格中有一个选择下拉菜单,当我尝试选择一个选项时,我想将整个对象发送到 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.

但是如果我设置 value={item.id} ,这可以正常工作而不会出现任何错误,但是我想发送整个对象而不仅仅是 id

4

1 回答 1

0

您不能将对象传递给值。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>
        );
      },
    },
]

如果您真的想始终传递一个对象,您可以创建自己的自定义组件来接收一个对象。这显然会比上述操作复杂得多。

于 2021-07-15T18:51:44.513 回答