我们在做一般项目的时候,经常会出现事件绑定的情况。这时候this的出现能帮助我们快速、准确的绑定某一事件,总结一下this的指向问题。

对于this的指向,我直接用三点来概括。
1.谁调用this就指向谁
2.es6箭头函数直接指向父层
3.部分this直接指向windows

举个例子

class Apa extends React.Component{
constructor(props){
  super(props);
  this.state={
    mag:'我是Home的事件'
  }
}
run(){
  alert('错啦!我是点击的事件');
}
render(){
  return(
    <div>
      <h3>{this.state.mag}</h3>
      <button onClick={this.run}>触发</button>
    </div>  
  );
}
}

首先类的方法默认是不会绑定this的。如果你忘记绑定 this.handleClick 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined。我们点击触发,会弹出run()函数中的内容。来看看下面的这个,假如我们需要在方法中使用数据呢?我们想把“我是home事件弹出来”

class Apa extends React.Component{
  constructor(props){
    super(props);
    this.state={
      mag:'我是Home的事件'
    }
  }
  run(){
    alert(this.state.mag);
  }
  render(){
    return(
      <div>
        <h3>{this.state.mag}</h3>
        <button onClick={this.run}>触发</button>
      </div>  
    );
  }
}

ben.png

报错了,是因为this没有正确的指向。
这时需要改变this的指向,才能正确显示。通过在onClick中指明当前应该指向Ape。使用bind()方法。

class Apa extends React.Component{
  constructor(props){
    super(props);
    this.state={
      mag:'我是Home的事件'
    }
  }
  run(){
    alert(this.state.mag);
  }
  render(){
    return(
      <div>
        <h3>{this.state.mag}</h3>
        <button onClick={this.run.bind(this)}>触发</button>
      </div>  
    );
  }
}

eee.png

在构造函数中改变this的指向

class Apa extends React.Component{
  constructor(props){
    super(props);
    this.state={
      mag:'我是Home的事件'
    }
    this.run = this.run.bind(this);
  }
  run(){
    alert(this.state.mag);
  }
  render(){
    return(
      <div>
        <h3>{this.state.mag}</h3>
        <button onClick={this.run}>触发</button>
      </div>  
    );
  }
}

通过箭头函数改变this的指向。(es6的语法糖真的很甜)

class Apa extends React.Component{
  constructor(props){
    super(props);
    this.state={
      mag:'我是Home的事件'
    }
    this.run = this.run.bind(this);
  }
  run = ()=>{
    alert(this.state.mag);
  }
  render(){
    return(
      <div>
        <h3>{this.state.mag}</h3>
        <button onClick={this.run}>触发</button>
      </div>  
    );
  }
}
//你也可以这样
class Apa extends React.Component{
  constructor(props){
    super(props);
    this.state={
      mag:'我是Home的事件'
    }
    this.run = this.run.bind(this);
  }
  run (){
    alert(this.state.mag);
  }
  render(){
    return(
      <div>
        <h3>{this.state.mag}</h3>
        <button onClick={() => this.run()}>触发</button>
      </div>  
    );
  }
}
//注意后面的run后面有()

此外再扩展一个双冒号法(双冒号法必须在没有传参的条件下运用。)

class Home extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
  };
 }
 del(){
  console.log('del')
 }
 render() {
  return (
   <div className="home">
    <span onClick={::this.del}></span>
   </div>
  );
 }
}
Last modification:October 19th, 2019 at 04:40 pm
如果觉得我的文章对你有用,请随意赞赏