【问题标题】:how to pass an object to an onchange function? (Select option)如何将对象传递给 onchange 函数? (选择选项)
【发布时间】:2021-09-24 15:03:09
【问题描述】:

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

【问题讨论】:

  • 这看起来像是您的代码的摘录。还有更多吗?
  • 我认为您收到此错误是因为您正在一一设置选择选项,而不是因为 onChange 事件。尝试使用数组设置选择选项
  • 你能告诉我怎么做吗? @Rukshán
  • 我使用了一个数组来设置选项@Rukshán

标签: javascript typescript drop-down-menu onchange select-options


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多