[英]onChange in react.js
I am new to react.js.我是 react.js 的新手。 I am little bit confused about onChange event in react.js.
我对 react.js 中的 onChange 事件有点困惑。 Why we are not using brackets while handling the event through onChange event?
为什么我们在通过 onChange 事件处理事件时不使用括号?
<input
type="text"
onChange={this.handleChange()}
/>
Normally when we handle the event through JavaScript we would write like this通常我们通过JavaScript处理事件的时候我们会这样写
<input type="text" onclick="handleChange()"/>
If you mean why we need to do onChange={this.handleChange}
instead of onChange={this.handleChange()}
- the first one makes gives a reference of handleChange to the onChange.如果你的意思是为什么我们需要做
onChange={this.handleChange}
而不是onChange={this.handleChange()}
- 第一个 make 给出了 handleChange 对 onChange 的引用。 The second one immediately (as it is interpreted) runs the handleChange function and the return value of that is saved as a referece for the onChange.第二个立即(按其解释)运行 handleChange function 并将其返回值保存为 onChange 的引用。
Think about it like this这样想
onClick={alert(123)} // this runs alert immediately
onClick={() => alert(1)} // makes a new function will run when clicked
onClick={alert} // this runs alert when clicked
If you need the event
object of in your event handler, think about where you would get that from;如果您的事件处理程序中需要
event
object ,请考虑从何处获取该事件; you need to get it as a function parameter and for that you need a new function or reference:您需要将其作为 function 参数获取,为此您需要一个新的 function 或参考:
onClick={console.log} // logs the event object
onClick={(event) => console.log(event)} // also logs the event
onClick={console.log(event)} // runs immediately, event doesn't exist then
When you have an inline event handler like onclick="handleChange()"
your browser actually evaluates the string "handleChange()"
as you press.当你有一个像
onclick="handleChange()"
这样的内联事件处理程序时,你的浏览器实际上会在你按下时评估字符串"handleChange()"
。 Like with the eval()
function. Try doing eval("alert()")
in dev tools and do note that there "alert()" is a string与
eval()
function 一样。尝试在开发工具中执行eval("alert()")
并注意“alert()”是一个字符串
PS.附言。 Welcome to SO: Please check the formatting of your question next time :)
欢迎来到 SO:请下次检查问题的格式:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.