React开发:如何获取传递给TodoItem的props以实现任务编辑
Fixing TodoItem Edit State Trigger in TodoList
Hey there! Let’s sort out how to correctly pass props to your TodoItem components so you can trigger the edit state properly when clicking a task.
First, let’s spot the issue in your current code:
- You’re trying to use
this.props.keyin theonEditmethod, but React doesn’t expose thekeyprop to components—it’s only used internally for reconciliation. So that value won’t be what you expect. - Right now, your
onEditmethod isn’t tied to a specific task—no matter whichTodoItemyou click, it’ll try to use the same (incorrect)selectedvalue.
Here’s the revised approach:
Update the
onEditmethod to accept a task ID parameter
This lets you specify exactly which task should be edited:onEdit = (itemId) => { this.setState({ edit: true, create: false, selected: itemId }); };Pass the specific task ID to
onEditwhen renderingTodoItem
Use an arrow function to wrap theonEditcall, so you can pass the current item’s_idas a parameter. We’ll also adjust theonCompletedhandler for consistency:const renderList = list.map(item => ( <TodoItem onEdit={() => this.onEdit(item._id)} onCompleted={() => this.onCompleted(item._id)} key={item._id} title={item.title} completed={item.completed} // Optional: Pass the item ID as a direct prop if TodoItem needs it internally itemId={item._id} /> ));
Why this works:
- The arrow function in
onEdit={() => this.onEdit(item._id)}captures the currentitem._idfrom the map loop, so eachTodoItemwill triggeronEditwith its own unique task ID. - You avoid the problem with the
keyprop by using the actualitem._iddirectly, which is accessible both in the parentTodoListand can be passed down toTodoItemif needed. - Inside your
TodoItemcomponent, you just need to callthis.props.onEdit()when the task is clicked (e.g., on a button press or title click) to trigger the edit state in the parent.
内容的提问来源于stack exchange,提问作者Helcio Oliveira
相关产品推荐
相关产品推荐

