简体   繁体   English

与普通的 onClick 函数不同,为什么 React 不渲染没有箭头函数调用的函数的元素?

[英]Why doesn't React render an element without function invoked by arrow function unlike normal onClick functions?

Why does this work?为什么这行得通?

<span onClick={()=>removeTodo(index)}>x</span>

But this doesn't work?但这不起作用?

<span onClick={removeTodo(index)}>x</span>

Full code完整代码

{todo.map((item, index) => {
  return (
    <pre className={index} key={index}>
      <h1 id={array}>{item}</h1>
      <span onClick={()=>removeTodo(index)}>x</span>
    </pre>
);
})}

The onClick function requires a short hand function syntax ()=>{} especially when you are calling a function and passing the parameters at the same time. onClick 函数需要简写函数语法()=>{} ,尤其是在调用函数并同时传递参数时。 It is also used when you are calling multiple functions inside onClick.当您在 onClick 中调用多个函数时也会使用它。

When to Use ()=> in onClick?何时在 onClick 中使用()=>

  1. Calling a function with a parameter调用带参数的函数
  2. Calling multiple function in a single onClick在单个 onClick 中调用多个函数
  3. Providing a function definition inside onClick在 onClick 中提供函数定义

When not to use?什么时候不使用?

  • Calling a function without a parameter调用不带参数的函数

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

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