【 React 】React 事件绑定的方式有哪些?有什么区别?

1. 是什么

在react应用中,事件名都是小驼峰格式进行书写,例如onclick要改写成onClick

最简单的绑定事件如下:

javascript 复制代码
class ShowAlert extends React.Component{
    ShowAlert(){
        console.log('hello')
    }
    render(){
        return <button onClick={this.ShowAlert}>show</button>
    }
}

从上面可以看到,事件绑定的方法需要使用{}包住
上述代码看似没有问题,但是当前处理函数代码或换成console.log(this)的时候,点击按钮,则会发现输出undefined****

2. 如何绑定

为了解决上面正确输出this问题,常见的绑定方式有:

  • render方法中使用bind
  • render方法中使用尖头函数
  • constructor中bind
  • 定义阶段使用箭头函数绑定

2.1 render方法中使用bind

如果使用一个类组件,在其中给某个元素/组件 一个onClick属性,他现在并会自定绑定其this到当前组件,解决这个问题的方法是在函数后使用.bind(this)将this绑定到当前组件中

javascript 复制代码
class App extends React.Component{
    handleClick(){
        console.log(this)
    }
    render(){
        return <div onClick={this.handleClick.bind(this)}>test</div>
    }
}

这种渲染方式每次render渲染的时候,都会重新进行bind操作,影响性能

2.2 render方法中使用箭头函数

通过ES6的上下文来将this的指向绑定给当前组件,同样再每一次render的时候都会生成新的方法,影响性能

javascript 复制代码
class App extends React.Component{
    handleClick(){
        console.log(this)
    }
    render(){
        return <div onClick={e=>this.handleClick.bind(e)}>test</div>
    }
}

2.3 constructor中bind

在constructor中预先绑定bind当前组件,可以避免render操作中重复绑定

javascript 复制代码
class App extends React.Component{
    constructor(props){
      super(props);
      this.handleClick=this.handClick.bind(this);
    }
    handleClick(){
        console.log(this)
    }
    render(){
        return <div onClick={this.handleClick.bind(this)}>test</div>
    }
}

2.4 定义阶段使用箭头函数绑定(最优)

跟上述方式三一样,能够避免在render操作中重复绑定,实现也非常简单,如下:

javascript 复制代码
class App extends React.Component{
    constructor(props){
      super(props)
    }
    handleClick=()=>{
        console.log(this)
    }
    render(){
        return <div onClick={this.handleClick}>test</div>
    }
}

3. 区别

上述四种方法的方式,区别如下:

编写方式:方式一方式二写法简单,方式三的编写过于冗杂

性能方面:方式一和方式二在每次组件render的时候都会生成新的方法实例,性能问题欠缺。若该函数作为属性值传给子组件的时候,都会导致额外的渲染,而方式三方式四只会生成一个方法实例

综上所述,方式四是最优的事件绑定方式

相关推荐
帅帅哥的兜兜18 分钟前
next.js实现项目搭建
前端·react.js·next.js
筱歌儿22 分钟前
css 左右布局
前端·css
GISer_Jing1 小时前
编译原理AST&以Babel为例进行解读、Webpack中自定义loader与plugin
前端·webpack·node.js
GISer_Jing1 小时前
Webpack中Compiler详解以及自定义loader和plugin详解
前端·webpack·node.js
浩~~1 小时前
CSS常用选择器
前端·css
于慨1 小时前
uniapp+vite+cli模板引入tailwindcss
前端·uni-app
yunvwugua__1 小时前
Python训练营打卡 Day26
前端·javascript·python
满怀10151 小时前
【Django全栈开发实战】从零构建企业级Web应用
前端·python·django·orm·web开发·前后端分离
Darling02zjh2 小时前
GUI图形化演示
前端
Channing Lewis2 小时前
如何判断一个网站后端是用什么语言写的
前端·数据库·python