iT邦幫忙

0

React 的事件觸發及事件綁定

一、事件觸發

JSX與HTML中的語法比較:
1.事件觸發在Html的寫法是全部小寫在JSX中是採用駝峰式命名法
2.呼叫函式由"action()"改為{this.action}

//html的按鈕寫法
<button onclick="action()">
  請按我
</button>
//JSX的按鈕寫法
<button onClick={this.action}>
  請按我
</button>

二、事件綁定

在事件中如果要使用到參數,就要綁定,沒有綁定就會出現錯誤。
見圖片

事件綁定的四種寫法

1.在class中的constructor中绑定事件:

import React from "react";

class ButtonTest extends React.Component {
  constructor(props){
      super(props);
      this.handleEdit = this.handleEdit.bind(this);  //綁定
  }
  handleEdit(event) {    //事件函式參數event,透過這個方法可以得到當事件發生時,發生事件的元素上的各種資訊。
     console.log('message',this.props);
  }
  
  render() {
      return <button onClick={this.handleEdit}>送出</button>
  }
}

export default ButtonTest;

2.在class中render中綁定事件

import React from "react";

class ButtonTest extends React.Component {
    handleEdit(event) {
        console.log('message',this.props);
        console.log('event',event);
    }
    
    render() {
        return <button onClick={this.handleEdit.bind(this)}>送出</button>  //綁定的位置
    }
}

export default ButtonTest;

3.使用箭头函数在 render 中绑定进行绑定

import React from "react";

class ButtonTest extends React.Component {
  handleEdit = (event) => {
       console.log('message',this.props);
   }
   
   render() {
       return <button onClick={this.handleEdit}>送出</button>
   }
}

export default ButtonTest;

4.使用匿名函数(箭头函数)与在 render 中進行绑定

import React from "react";

class ButtonTest extends React.Component {
  handleEdit(event) {
      console.log('message',this.props);
      console.log('event',event);
  }
  
  render() {
      return <button onClick={() => this.handleEdit(this)}>送出</button>
  }
}

export default ButtonTest;

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言