Saturday, December 28, 2019

[ReactJS][Examples] Use "this" in component methods

Since class methods is not bound by default, you need to bind "this" to methods mamually for using this in JSX callback, there are 3 methods bind "this" to methods offically:
Common html using in 3 examples in this article:
<div id="root"></div>

JavaScript

Method 1) bind this in contructor

class Button extends React.Component {
  constructor(props){
    super(props);
    this.state = {isOn:true};
    this.buttonClick = this.buttonClick.bind(this);
  }
  buttonClick(){
    if(this.state.isOn)
      this.setState({"isOn":false});
    else
      this.setState({"isOn":true});
  }
  render() {
    return (
      <button onClick={this.buttonClick}>
        {this.state.isOn?"ON":"OFF"}
      </button>
    );
  }
}
ReactDOM.render(<Button />,document.getElementById('root')); 

Method 2) bind this within handleClick

class Button extends React.Component {
  constructor(props){
    super(props);
    this.state = {isOn:true};
  }
  buttonClick = ()=>{
    if(this.state.isOn)
      this.setState({"isOn":false});
    else
      this.setState({"isOn":true});
  }
  render() {
    return (
      <button onClick={this.buttonClick}>
        {this.state.isOn?"ON":"OFF"}
      </button>
    );
  }
}
ReactDOM.render(<Button />,document.getElementById('root'));

Method 3) using experimental syntax

class Button extends React.Component {
  constructor(props){
    super(props);
    this.state = {isOn:true};
  }
  buttonClick(){
    if(this.state.isOn)
      this.setState({"isOn":false});
    else
      this.setState({"isOn":true});
  }
  render() {
    return (
      <button onClick={(e)=>{this.buttonClick(e)}}>
        {this.state.isOn?"ON":"OFF"}
      </button>
    );
  }
}
ReactDOM.render(<Button />,document.getElementById('root'));

No comments :

Post a Comment