React-組件的事件處理和狀態更新

組件的事件處理和狀態更新

  1. 新增一個Message組件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    import React, {Component} from 'react';     //載入react核心

    class Message extends Component{ //創建一個Message組件
    //組件狀態
    state = {
    'title': 'Hello',
    'name': 'John'
    };

    //自訂涵式
    changeName = () =>{ //使用箭頭涵式確保this指向此組件
    this.setState({ //使用setState變更state的內容
    'name': 'Bob',
    })
    }

    //生命週期內的涵式
    render() {
    return(
    <div> //this指向此組件
    <h1> { this.state.title } </h1>
    <h3>I am { this.state.name }</h3>
    //JSX,所以onClick要用駝峰式
    <button onClick= {this.changeName}>更改state</button>
    </div>
    )
    }
    }

    export default Message;
  2. 新增一個index.js(此為預設的進入點,找到所import進來的模組,再下去找其他檔案import的模組)

    1
    2
    3
    4
    5
    6
    import React from 'react';                      //載入react核心
    import ReactDom from 'react-dom'; //載入react-dom核心
    import Message from './Message'; //載入Message.js

    ReactDom.render(<Message/>, document.getElementById('root'))
    //render第一個參數是element,第二個參數是DOM container
  3. 網頁呈現畫面

    點擊BUTTON按鈕之後,變更state的內容

分享到