tags: React, onClick, 额外参数, 获取 value
# TL’DR
## 不使用 this
1 | <button onClick={this.handleRemove} value={id} abc={id} data-bcd={id}> |
## 使用 this
1 |
|
1 | /* binding is important */ |
# React: Handling Events
几个要点:
* React events are named using camelCase, rather than lowercase.
* With JSX you pass a function as the event handler, rather than a string.
For example, the HTML:
1 | <button onclick="activateLasers()"> |
is slightly different in React:
1 | <button onClick={activateLasers}> |
Another difference is that you cannot return false
to prevent default behavior in React. You must call preventDefault
explicitly.
防止默认事件的代码需要一些修正
1 | <a href="#" onclick="console.log('The link was clicked.'); return false"> |
In React, this could instead be:
1 | function ActionLink() { |
When using React you should generally not need to call addEventListener
to add listeners to a DOM element after it is created.
Instead, just provide a listener when the element is initially rendered.
初始化的时候给事件管理器,DOM初始化之后就别去添加其他监听器了。
JQuery: …
## 示例
1 | class Welcome extends React.Component{ |
## Passing Arguments to Event Handlers
下方的ID代表对应数据编号, 既可以使用外部的循环Index.
这儿有点像是闭包, 区别在于是否将 event 传进去
1 | <button onClick={(e) => this.deleteRow(arg1, arg2, e)}>Delete Row</button> |
两种模式类似
1. 对于 Arrow Function 来说, 需要显式传入
1. 对于 bind() 来说就不用了
1. 另外如果 event 不重要的话不传其实也可以
来源: https://reactjs.org/docs/handling-events.html
## Get attr ‘value’
注意以下情况情况没有直接传递任何参数, event 指向当前 event, 然后通过获取到这个 elem 再获取其他参数
1 | <button onClick={this.handleRemove} value={id} abc={id} data-bcd={id}> |