首页 > 解决方案 > How to pass custom attributes onClick in React

问题描述

I want to pass custom attribute task to function. following is the code but it is giving undefined

function handleChange(e)
{
   console.log(e.target.task)
}


const listTask = props.tasks.map((task)=>
{
   return(
      <option key={task._id} task={task}>{task.title}</option>
   )
})

return(

<select onChange={handleChange}>
       {listTask}
</select>
)

in handleChange method, I want to access task attribute is there any way?

标签: javascriptreactjs

解决方案


你可以试试这个

function handleChange(e, task) {
  console.log(task)
}


<select onChange={e => handleChange(e, task)}>
  <option key={task._id} task={task}>
    {task.title}
  </option>
</select>


参考:将参数传递给事件处理程序


推荐阅读