You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.key in the onEdit method, but React doesn’t expose the key prop to components—it’s only used internally for reconciliation. So that value won’t be what you expect.
  • Right now, your onEdit method isn’t tied to a specific task—no matter which TodoItem you click, it’ll try to use the same (incorrect) selected value.

Here’s the revised approach:

  1. Update the onEdit method 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 
      });
    };
    
  2. Pass the specific task ID to onEdit when rendering TodoItem
    Use an arrow function to wrap the onEdit call, so you can pass the current item’s _id as a parameter. We’ll also adjust the onCompleted handler 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 current item._id from the map loop, so each TodoItem will trigger onEdit with its own unique task ID.
  • You avoid the problem with the key prop by using the actual item._id directly, which is accessible both in the parent TodoList and can be passed down to TodoItem if needed.
  • Inside your TodoItem component, you just need to call this.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:12:30