[React 04] props


Posted by tzutzu858 on 2021-04-25

props (function component 寫法)

function component 可以接收一個參數叫 props,那要怎麼去用它,跟用 html 的元素一樣,設定一個 name="tzu",叫出來用 props.name 就可以了
補充: {} 裡面可以寫 js 程式碼,沒有 {} 會被解讀成純文字

function Hello(props) {
    return (
        <div>
            <h1> 這是 function component</h1>
            <h2>hello {props.name}</h2>  // 畫面印出 hello tzu
        </div>
    )
}

const rootElement = document.getElementById("root")
ReactDOM.render(<Hello name="tzu" />, rootElement)

ES6 解構寫法

function Hello({ name }) {
    return <h2>hello {name}</h2> // 畫面印出 hello tzu
}

const rootElement = document.getElementById("root2")
ReactDOM.render(<Hello name="tzu" />, rootElement)

props children (function component)

function Hello({ children }) {
    return <h2> hello {children}</h2> // 畫面印出 hello tzutzu

}

const rootElement = document.getElementById("root2")
ReactDOM.render(
    <Hello>
        tzutzu
    </Hello>, rootElement
)

props (class component 寫法)

state : 內部元件的狀態

props : 外部傳進來的狀態



props.children (class component)

可以傳任意元素進去( 字串、HTML 元素、Component… )
把上面圖片裡的程式碼做點更動變成下面,一樣可以拿到值

import React, { Component } from 'react'

class Counter extends Component {
    render() {
        return <div>{this.props.children}</div>;
    }
}

class App extends Component {
    constructor() {
        super()
        this.state = {
            counter: 1
        }
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
        this.setState({
            counter: this.state.counter + 1
        })
    }

    render() {
        return (
            <div>
                <h1 onClick={this.handleClick}>click me!!</h1>
                <Counter>
                    {this.state.counter}
                </Counter>
            </div>
        )
    }
}

export default App

流程是 :

  1. state.counter = 1,畫面輸出 1
  2. 點了一下 handleClick,改變了 state,state.counter = 2,重新 render()
    畫面輸出 2

在 React 裡面,只要 state 一改變,就會更新 UI ,也就是觸發 render()











Related Posts

MTR04_1023

MTR04_1023

Take a Ten Minutes Walk

Take a Ten Minutes Walk

明文儲存密碼原理與檢測方法 - 以OO壽司為例

明文儲存密碼原理與檢測方法 - 以OO壽司為例


Comments