问题描述
我在表中有一个选择下拉列表,当我尝试选择一个选项时,我想将整个对象发送到 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
解决方法
您不能将对象传递给值。 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>
);
},]
如果你真的想总是传递一个对象,你可以创建自己的自定义组件来接收一个对象。显然,这比执行上述操作要复杂得多。