栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

详解react关于事件绑定this的四种方式

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解react关于事件绑定this的四种方式

在react组件中,每个方法的上下文都会指向该组件的实例,即自动绑定this为当前组件,而且react还会对这种引用进行缓存,以达到cpu和内存的最大化。在使用了es6 class或者纯函数时,这种自动绑定就不复存在了,我们需要手动实现this的绑定

React事件绑定类似于DOM事件绑定,区别如下:

1.React事件的用驼峰法命名,DOM事件事件命名是小写

2.通过jsx,传递一个函数作为event handler,而不是一个字符串。

3.React事件不能通过返回false来阻止默认事件,需要显式调用preventDefault()

如下实例:


Click me


class Actionlink extends React.Component {
constructor(props) {
super(props);
}

handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}

render() {
return (
Click Me...
);
}

}

ps:React组件类的方法没有默认绑定this到组件实例,需要手动绑定。

以下是几种绑定的方法:

bind方法

直接绑定是bind(this)来绑定,但是这样带来的问题是每一次渲染是都会重新绑定一次bind;

class Home extends React.Component {

 constructor(props) {
  super(props);
  this.state = {
  };
 }

 del(){
  console.log('del')
 }

 render() {
  return (
   
    
   
  );
 }
}

构造函数内绑定

在构造函数 constructor 内绑定this,好处是仅需要绑定一次,避免每次渲染时都要重新绑定,函数在别处复用时也无需再次绑定

class Home extends React.Component {

 constructor(props) {
  super(props);
  this.state = {

  };
  this.del=this.del.bind(this)
 }

 del(){
  console.log('del')
 }

 render() {
  return (
   
    
   
  );
 }
}

::不能传参

如果不传参数使用双冒号也是可以

class Home extends React.Component {

 constructor(props) {
  super(props);
  this.state = {

  };
 }

 del(){
  console.log('del')
 }

 render() {
  return (
   
    
   
  );
 }
}

箭头函数绑定

箭头函数不仅是函数的'语法糖',它还自动绑定了定义此函数作用域的this,因为我们不需要再对它们进行bind方法:

class Home extends React.Component {

 constructor(props) {
  super(props);
  this.state = {

  };

 }

 del=()=>{
  console.log('del')
 }

 render() {
  return (
   
    
   
  );
 }
}

以上几种方法都可以实现this绑定,使用那种各自的习惯;希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/82010.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号