react中的this

1 在constructor中绑定

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
 
    // 这边绑定是必要的,这样 `this` 才能在回调函数中使用
    this.handleClick = this.handleClick.bind(this);
  }
 
  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
 
  render() {
    return (
      
    );
  }
}
 
ReactDOM.render(
  ,
  document.getElementById('example')
);

2 在onClick事件中写箭头函数

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
  }
 
  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
 
  render() {
    return (
      
    );
  }
}
 
ReactDOM.render(
  ,
  document.getElementById('example')
);

3 使用bind绑定this

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
  }
 
  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
 
  render() {
    return (
      
    );
  }
}
 
ReactDOM.render(
  ,
  document.getElementById('example')
);

 

 

 

 

 

你可能感兴趣的:(react)