简体   繁体   English

从 React Hooks 中的购物项目中删除项目

[英]Remove item from Shopping Items in React Hooks

While working on a Codecadamy exercise on React Hooks, I came across a code that I couldn't understand.在进行关于 React Hooks 的 Codecadamy 练习时,我遇到了一段我无法理解的代码。

Check this in the following code: onClick={() => removeItem(index)}在以下代码中检查: onClick={() => removeItem(index)}

 <ul>{cart.map((item,index) => <li key={index} onClick={() => removeItem(index)} >{item}</li>)}</ul>

Why can't we simply write: onClick={removeItem(index)} // When I tried doing it, the code didn't work.为什么我们不能简单地写: onClick={removeItem(index)} // 当我尝试这样做时,代码不起作用。

While I have completed the code, I can understand the difference between onClick={removeItem(index)} and onClick={() => removeItem(index)} .虽然我已经完成了代码,但我可以理解onClick={removeItem(index)}onClick={() => removeItem(index)}之间的区别。

In the same code, following example worked well (when I tried to add the item in a list.)在相同的代码中,以下示例运行良好(当我尝试将项目添加到列表中时。)

{produce.map((item) => <button key={item} value={item} onClick={addItem}>{item}</button>)};

In the above example, onClick={addItem} worked well.在上面的例子中, onClick={addItem}运行良好。

Here is complete code: https://gist.github.com/sixpl/8141196fc688949ccb51b4459e645b34这是完整的代码: https : //gist.github.com/sixpl/8141196fc688949ccb51b4459e645b34

Thank you for your time.感谢您的时间。

While using {removeItem(argument)} , you are actually making a function call.在使用{removeItem(argument)} ,您实际上是在进行函数调用。 The JSX expression (what you have mentioned inside inside { } ) will get evaluated and this function will be called. JSX 表达式(您在{ }提到的内容)将被评估并调用此函数。 Wrapping it inside a function ensures that the we are indicating what to call on click but not calling it.将它包装在一个函数中可以确保我们指示点击时调用什么而不是调用它。 Ex: {()=>{ yourActualFunctionCall(argument) }}例如: {()=>{ yourActualFunctionCall(argument) }}

While using {addItem} , you are indicating that the function to be called on click is addItem .使用{addItem} ,您表示单击时要调用的函数是addItem Notice, there is no ( ) after the function, so the addItem will not be called.请注意,函数后面没有( ) ,因此不会调用addItem

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM