React-注册事件

注册事件

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值