为什么索引 A Class 来自在 React Hooks 中使用 map 函数的渲染列表?
Why Is The index A Class From A Rendered List Using map Function In React Hooks?
我使用 react hooks 和 useReducer 创建了一个简单的列表应用程序。
添加项目时列表呈现没有问题,但单击按钮删除项目时出现问题。什么都没发生。
当我 console.log 时,从 map 函数索引传递的索引是 class。
为什么会这样?
在 StackBlitz 上查看下面的代码:
https://stackblitz.com/edit/react-jxgqwc
我希望索引是 listItems 数组中某个项目的索引,而不是 class。
它是 React Click-Event。
将按钮上的 click-event 更改为:
onClick={() => handleItemDelete(index)}
然后就可以了。
onClick EventHandler 的默认参数是一个点击事件,控制台显示为 Class.
参见:https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers
问题是你没有将索引传递给 handleItemDelete
https://stackblitz.com/edit/react-siywgo?file=index.js
下面是主要涉及的两段代码:
const handleItemDelete = (index) => {
console.log(index) //<==== why is index is a class?
dispatch({
type: "DELETE_ITEM",
itemId: index,
});
};
<ul>
{items.map((item, index) => (
<li key={index.toString()}>
{item}{" "}
<button
onClick={handleItemDelete}
>
X
</button>
</li>
))}
</ul>
当onClick
事件发生时,传递给它的东西将是event
对象。如果你想要索引,那么你需要这样的东西:onClick={()=>handleItemDelete(index)}
.
这是您的代码的修改版本:
我使用 react hooks 和 useReducer 创建了一个简单的列表应用程序。 添加项目时列表呈现没有问题,但单击按钮删除项目时出现问题。什么都没发生。 当我 console.log 时,从 map 函数索引传递的索引是 class。 为什么会这样?
在 StackBlitz 上查看下面的代码:
https://stackblitz.com/edit/react-jxgqwc
我希望索引是 listItems 数组中某个项目的索引,而不是 class。
它是 React Click-Event。
将按钮上的 click-event 更改为:
onClick={() => handleItemDelete(index)}
然后就可以了。 onClick EventHandler 的默认参数是一个点击事件,控制台显示为 Class.
参见:https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers
问题是你没有将索引传递给 handleItemDelete https://stackblitz.com/edit/react-siywgo?file=index.js
下面是主要涉及的两段代码:
const handleItemDelete = (index) => {
console.log(index) //<==== why is index is a class?
dispatch({
type: "DELETE_ITEM",
itemId: index,
});
};
<ul>
{items.map((item, index) => (
<li key={index.toString()}>
{item}{" "}
<button
onClick={handleItemDelete}
>
X
</button>
</li>
))}
</ul>
当onClick
事件发生时,传递给它的东西将是event
对象。如果你想要索引,那么你需要这样的东西:onClick={()=>handleItemDelete(index)}
.
这是您的代码的修改版本: