1. 程式人生 > >React 事件 4

React 事件 4

將引數傳遞給事件處理程式

在迴圈內部,通常需要將額外的引數傳遞給事件處理程式。例如,如果id是行ID,則以下任何一個都可以工作:

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

在這兩種情況下,e表示React事件的引數將作為ID之後的第二個引數傳遞。使用箭頭函式,我們必須顯式傳遞它,但bind任何進一步的引數都會自動轉發。

下面是3個點選事件的Demo:

1.使用bind的繫結事件:

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

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

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

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

2.使用元件屬性等於一個函式的繫結事件

class LoggingButton extends React.Component {
  constructor(props){
    super(props);
    this.state = {a:12}
  }
  handleClick = () => {
    console.log('this is:', this);
    this.setState(state=>({
      a:123 
    }));
  }

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

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

3.在回撥中使用箭頭函式

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}