23 June 2018

ReactJS: Event handler Function - Bắt sự kiện Click bằng 2 cách gọi function

Start project
Arrow function event
ReatcJS 2018
class ToggleButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isOn: true}; //this.state.isOn = true;
  }
  btnClick = () => {
    this.setState(prevState =>({
        isOn: !prevState.isOn
      }
    ))
  }
  render() {
    return(
      <button className="btn btn-primary" onClick={this.btnClick}>
        This is toggle button {this.state.isOn ? "ON": "OFF"}
      </button>
    );
  }
}

ReactDOM.render(
  <ToggleButton />
  ,document.getElementById('root'));
Function event
ReatcJS 2018
class ToggleButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isOn: true}; //this.state.isOn = true;
    this.btnClick = this.btnClick.bind(this); //Binding handle function
  }
  btnClick() {
    this.setState(prevState =>({
        isOn: !prevState.isOn
      }
    ))
  }
  render() {
    return(
      <button className="btn btn-primary" onClick={this.btnClick}>
        This is toggle button {this.state.isOn ? "ON": "OFF"}
      </button>
    );
  }
}

ReactDOM.render(
  <ToggleButton />
  ,document.getElementById('root'));

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang