简体   繁体   English

带箭头的 React.js 事件 function 与没有任何 () function

[英]React.js event with arrow function vs without any () function

hello i am wondering why only normal functions like below works and arrow functions do not.您好,我想知道为什么只有像下面这样的正常功能有效而箭头功能无效。

const Form = () =>{

    const [text, setText] = useState("");

    const handle=(e)=>{
       setText(e.target.value);
    }
    const alertText = (e) =>{
       console.log(text);
       alert(text);
    }

    return(
       <>
           <input onChange={handle}></input>
           <button onClick={alertText}>submit</button>
           <h1>{text}</h1>   
       </>
    )}

using arrow functions like <input onChange={()=>handle}> doesn't work at all and I have no idea what the difference between of them.使用像<input onChange={()=>handle}>这样的箭头函数根本不起作用,我不知道它们之间有什么区别。

Well, that's because if you use an arrow function on the element you have to call it like this:好吧,那是因为如果你在元素上使用箭头 function 你必须这样称呼它:

<input onChange={(e)=>handle(e)}>

component expects onChange as a function, that function will be called when the user changes the value of the input.组件期望 onChange 为 function,当用户更改输入值时将调用 function。

NOTE: It's syntactically correct but the handle function will not execute.注意:语法正确,但句柄 function 不会执行。

When you do当你这样做

<input onChange={handle}></input>
// it's equivalent to
<input onChange={(e)=>{ setText(e.target.value); }}></input>

But when you do但是当你这样做时

<input onChange={()=>handle}></input>
// it's equivalent to
<input onChange={(e) => ()=>{ setText(e.target.value);}}></input>

You can do:你可以做:

 <input onChange={(e)=>handle(e)}>

You are not passing the event into the handle function您没有将事件传递到句柄 function

 <input onChange={()=>handle}> 

In above case onChange is assigned a function which has a single statement handle inside it.在上述情况下,onChange 被分配了一个 function,其中有一个语句handle So onclick the statement handle is run.所以 onclick 语句handle运行。 nothing happens.什么都没发生。

 <input onChange={()=>handle()}> 

In above case onChange is assigned a function which has a single statement handle() inside it.在上述情况下,onChange 被分配了一个 function ,其中有一个语句handle() So onclick handle is executed.所以 onclick 句柄被执行。

<input onChange={handle}>

In above case onChange is assigned handle function.在上述情况下,onChange 被分配了句柄 function。 So onclick handle is executed.所以 onclick 句柄被执行。

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

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