iT邦幫忙

2021 iThome 鐵人賽

0
自我挑戰組

Be friend with JavaScript系列 第 34

React - Props & State

React Component 只能透過資料狀態的改變來更新畫面,而 React 元件有兩種資料來源:

  1. 透過外部傳進來 component 的 Props
  2. 在 component 內部被管理的 State

當 Props 或 State 改變時才會更新畫面。

Props - 由外部傳入的屬性

  • React 的每個 component 都是 function,我們會在 function 裡面放入參數,所以也可以在 React component 放入參數,而在 commponent 的參數就稱為 props(即 properties 屬性)。
  • component 接收任意的 props 並回傳描述畫面的 React element。
  • props 是 React 父元件和子元件間的橋樑,屬性唯獨,不能被改變,且只能由上傳到下(父傳子)。

舉個簡單的例子:
在 App.js 將 name 屬性傳遞給 Welcome.js 做使用

// App.js
import Welcome from "./Welcome";
function App() {
  return (
      <Welcome name="Mary"/>
  );
}
export default App;

Welcome.js 接收 props

// Welcome.js
import React from 'react'
const Welcome = (props) => {
    return (
        <h1>Hello, {props.name}</h1>
    )
}
export default Welcome

或者也可以解構賦值來接收 props,直接將要傳遞的屬性名稱放入參數裡面,這樣的做法就不用每次都一直寫 props 了,也可以比較清楚知道是什麼資料被傳進去

// Welcome.js
import React from 'react'
const Welcome = ({ name }) => {
    return (
        <h1>Hello, { name }</h1>
    )
}
export default Welcome

若使用 class component,則要將 render() 內的 props 替換成 this.props:

// Welcome.js
import React, { Component } from 'react';
class Welcome extends Component {
    render() {
      return <h1>Hello, {this.props.name}</h1>;
    }
}
export default Welcome

無論是使用 function component 或是 class component 最終結果都相同,網頁上都會顯示 Hello, Mary
https://ithelp.ithome.com.tw/upload/images/20211005/20140282M27lsNZQPH.jpg

State - 狀態

  • 可自由讀寫
  • 只能在 Class Components 中使用,在 function component 則會使用 Hook - useState(下一篇會介紹)。
  • 在 Class component 中的 constructor() 中會使用 this.state 來初始化 State 物件(給預設值),且使用 this.setState() 來更新 State 讓畫面重新渲染。

例如:

import React, { Component } from "react";
class ClassState extends Component {
  constructor() {
    // super 呼叫 component 的 constructor
    super();
    // count 的初始值設為 0
    this.state = { count: 0 };
  }
  render() {
    return (
      <div>
        <h3>Class component - state</h3>
        <p>You clicked {this.state.count} times</p>
        <button
          onClick={() => {
            // 利用 setState 改變狀態,使 component 重新 render
            this.setState({ count: this.state.count + 1 });
          }}
        >
          Click
        </button>
      </div>
    );
  }
}
export default ClassState;

上面的例子因為 constructor() 內 count 初始值設為 0,打開網頁會看到畫面如下:
https://ithelp.ithome.com.tw/upload/images/20211005/20140282GL6VZJn7dc.jpg
利用 this.setState() 改變狀態時,點擊按鈕時畫面就會更新,點擊幾次畫面就會被更新幾次,下圖為點擊按鈕 10 次後的畫面,被點擊的次數變成 10。
https://ithelp.ithome.com.tw/upload/images/20211005/20140282fP8ApTTp5D.jpg

參考資料:
https://www.fooish.com/reactjs/state.html


上一篇
建立 React component
下一篇
React Hooks - useState
系列文
Be friend with JavaScript39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言