react事件處理函數(shù)及事件

為react元素添加事件處理函數(shù)的方法:
一、在類中有三種方法:
  1. 在構(gòu)造函數(shù)中用bind
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 為了在回調(diào)中使用 `this`,這個(gè)綁定是必不可少的
    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')
);
  1. 用箭頭函數(shù)的方式
class LoggingButton extends React.Component {
  // 此語法確保 `handleClick` 內(nèi)的 `this` 已被綁定。
  // 注意: 這是 *實(shí)驗(yàn)性* 語法。
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
  1. 在回調(diào)中使用[箭頭函數(shù)
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // 此語法確保 `handleClick` 內(nèi)的 `this` 已被綁定。
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

以上三種方法個(gè)人覺得使用第二種方法比較好。

react元素事件函數(shù)傳遞參數(shù)的方式

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

這里的e是事件對(duì)象,包含事件相關(guān)信息。具體見https://react.docschina.org/docs/events.html

react元素自帶多個(gè)事件處理函數(shù)

詳見https://react.docschina.org/docs/events.html

這里面要提一下onScroll事件函數(shù),這個(gè)事件函數(shù)只對(duì)跟組件有效,因?yàn)閟croll只是根組件發(fā)生了滾動(dòng),其他子組件相對(duì)于根組件都沒有發(fā)生變化。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容