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.
CodePudding user response:
component expects onChange as a function, that function will be called when the user changes the value of the input.
NOTE: It's syntactically correct but the handle function will not execute.
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>
CodePudding user response:
Well, that's because if you use an arrow function on the element you have to call it like this:
<input onChange={(e)=>handle(e)}>
CodePudding user response:
You can do:
<input onChange={(e)=>handle(e)}>
You are not passing the event into the handle function
CodePudding user response:
<input onChange={()=>handle}>
In above case onChange is assigned a function which has a single statement handle inside it. So onclick the statement handle is run. nothing happens.
<input onChange={()=>handle()}>
In above case onChange is assigned a function which has a single statement handle() inside it. So onclick handle is executed.
<input onChange={handle}>
In above case onChange is assigned handle function. So onclick handle is executed.
