iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 8
0
Modern Web

30天React從入門到入坑系列 第 8

DAY8:Handling Events

React事件基於W3C spec定義SyntheticEvent(合成事件),它完全符合W3C標準。不會有任何瀏覽器支援度的問題,React事件援用駝峰式命名onClick,而HTML命名方式全小寫onclick,所以撰寫式需注意命名方式。React事件綁定不是直接綁定在DOM,而是在結構最外層使用事件監聽器統一處理(Event delegation),監聽器儲存內部的事件監聽與處理函數。當元件掛載或移除時,只需要針對監聽器進行插入或移除物件。

SyntheticEvent attribute

boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
DOMEventTarget target
number timeStamp
string type

SyntheticEvent詳細資訊參考:https://reactjs.org/docs/events.html

handleClick constructor宣告:在constructor內綁定this

src/SayHi.js

import React, { Component } from 'react';

class SayHi extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {date: new Date()};
  }

  handleClick() {
    this.setState({date: new Date()});
  }

  render() {
    return <h1 onClick={this.handleClick}>{this.state.date.toLocaleTimeString()} Hi, {this.props.name}</h1>;
  }
}

export default SayHi;

handleClick arrow function:會自動綁定this,所以不需要再額外使用bind

src/SayHi.js

import React, { Component } from 'react';

class SayHi extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  handleClick = () => {
    this.setState({date: new Date()});
  }

  render() {
    return <h1 onClick={this.handleClick}>{this.state.date.toLocaleTimeString()} Hi, {this.props.name}</h1>;    
  }
}

export default SayHi;

上一篇
DAY7:React Lifecycle
下一篇
DAY9:Conditional Rendering
系列文
30天React從入門到入坑30

尚未有邦友留言

立即登入留言