React使用的思考总结

1、事件处理中的this指针问题

在 react 中,用 class 声明一个组件,调用 class 中的方法时,如果该方法中有 this 且没有手动绑定 this 指针,则会发生 this 指向 undefined 的问题。

class LoggingButton extends React.Component {
constructor(props) {
    super(props);
    this.state = {isToggleOn: true}
  }
   handleClick() {
    this.setState(prevState => ({  //报错,this 指向 undefined,没有setState方法
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

1.1、如何手动绑定方法中的 this 指针

1.1.1、在构造函数中用 bind 绑定 this

constructor(props) {
    //下面手动绑定了handleClick方法的this指针
    this.handleClick = this.handleClick.bind(this);
}

1.1.2、在调用时用 bind 绑定 this

class Test extends React.Component {
    constructor (props) {
        super(props)
        this.state = {message: 'Allo!'}
    }

    handleClick (name, e) {
        console.log(this.state.message + name)
    }

    render () {
        return (
            <div>
                //下面在调用时绑定了this指针,并进行了传参   
                <button onClick={ this.handleClick.bind(this, '赵四') }>Say Hello</button>
            </div>
        )
    }
}

1.1.3、用箭头函数声明函数

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isToggleOn: true };
  }

  //用箭头函数声明可以绑定this
  handleClick = () => {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

1.1.4、用箭头函数调用class中的函数

render() {
    return (
     //用箭头函数来调用
      <button onClick={(e) => {this.handleClick(params, e)} }>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
}

使用这个语法有个问题就是每次在组件渲染的时候都会创建一个不同的回调函数,如果这个回调函数作为一个属性值传入其它组件,这些组件可能会进行额外的重新渲染。我们通常建议在构造函数中绑定或使用箭头函数声明函数的方式来避免这类性能问题。

1.1.5、使用React.createClass

React 15及以下的版本可以React.createClass函数来创建一个组件。你在里面创建的所有函数的this将会自动绑定到组件上。

const App = React.createClass({
 handleClick() {
  console.log('this', this); // this 指向App组件本身
 },
 render() {
  return (
   <div onClick={this.handleClick}>test</div>
  );
 }
});

但是需要注意随着React 16版本的发布官方已经将改方法从React中移除

1.2、为什么要手动绑定 this

还是有点模糊,给出一些参考链接

参考:http://www.fly63.com/article/detial/1013https://www.cnblogs.com/dashnowords/p/9343383.html