[英]How can I send my {todo.id} in a child component to my parent component's handler?
I am able to confirm that my handler is receiving the event, but I want to be able to refer to the actual key={todo.id}
, (or just the {todo}
), that my anchor tag is attached to inside the handler, because I want this as a reference to set my state. 我能够确认我的处理程序正在接收该事件,但是我希望能够引用实际的
key={todo.id}
,(或仅参考{todo}
),我的锚标签已附加到处理程序,因为我希望以此作为设置状态的参考。 Can someone please tell me how I would do this? 有人可以告诉我我该怎么做吗?
import React from 'react';
const Todo = props => (
<div>
<ul className = "list-group">
{props.todos.map(todo => {
return <li className = "list-group-item" key ={todo.id}>{todo.text}<a onClick={props.onDelete}
className="glyphicon glyphicon-trash" href="#"></a></li>
})
}
</ul>
</div>
);
export default Todo;
That's the child where you can see key={todo.id}
as well as the {props.onDelete}
handler ^^^. 那是您可以看到
key={todo.id}
和{props.onDelete}
处理程序^^^的{props.onDelete}
。
I then have this handler in my parent component, so how can I refer to it inside this handler?: 然后,我在父组件中有此处理程序,那么如何在该处理程序中引用它呢?
handleDelete(){
console.log();
}
Thanks for your help in advance! 谢谢您的帮助!
You could eg create a new inlined arrow function for each todo and pass the todo
as argument to onDelete
that way: 例如,您可以为每个待办事项创建一个新的内联箭头函数,然后将
todo
作为参数传递给onDelete
:
<a
onClick={() => props.onDelete(todo)}
className="glyphicon glyphicon-trash"
href="#"
/>
If you don't want to create a new function for each todo in each render, you could put the todo.id
in a data
attribute: 如果您不想为每个渲染中的每个待办事项创建新功能,则可以将
todo.id
放在data
属性中:
<a
onClick={props.onDelete}
className="glyphicon glyphicon-trash"
href="#"
data-id={todo.id}
/>
// ...
handleDelete(event) {
const todoId = event.target.dataset.id;
console.log(todoId);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.