文章目录
注册事件
React 元素的事件处理与 DOM 元素有些不同,React 通过事件绑定属性的方式注册事件时要采用驼峰式命名,其对应的属性值为一个函数而不是字符串。
示例:
import React from 'react'
import ReactDOM from 'react-dom'
class Hello extends React.Component {
render() {
return (
<div>
{
/* 驼峰命名,值为当前组件的相关函数 */}
<button onClick={
this.fun}>按钮</button>
</div>
)
}
fun() {
console.log('触发了点击事件!')
}
}
ReactDOM.render(<Hello />, document.getElementById('root'))
事件处理函数中 this 问题
在 React 中通过 class 创建的组件,其绑定的事件处理函数中的 this 值为 undefined
,通常需要将事件处理函数中的 this 指向当前组件实例,介绍几种处理 this 指向的方法:
方法一:在调用事件处理函数时通过 bind()
方法手动去指定 this
import React from 'react'
import ReactDOM from 'react-dom'
class Hello extends React.Component {
render () {
return (
<div>
{
/* 通过 bind() 将 this 修改为当前实例 */}
<button onClick={
this.func.bind(this)}>this 指向1</button>
</div>
)
}
func () {
console.log('调用了 func()')
console.log(this)
}
}
ReactDOM.render(<Hello />, document.getElementById('root'))
方法二:直接在构造器中修改事件处理函数的 this
import React from 'react'
import ReactDOM from 'react-dom'
class Hello extends React.Component {
constructor(props) {
super()
// 修改 this
this.show= this