iT邦幫忙

2021 iThome 鐵人賽

DAY 4
0
Software Development

30天學會React系列 第 5

Day5 State vs Props

前言

State跟Props這兩個東西其實不會很難,卻很重要,基本上你在寫React的日子裡都會一直碰到他們,可能會換個形式出現,卻永遠沒有消失,講到這就可以看出他們的重要性,那我們話不多說,進入主題!

現實案例

這邊為了方便各位了解,我說個案例,後面會把State跟Props帶入到故事中,方便大家釐清

不知道各位離開學校多久了?筆者剛離開學校滿一年(好懷念...),還記得開學的時候會發課本嗎?班長會把厚厚一疊課本放在第一排,然後由第一排往後傳遞,傳到最後一個。但因為你在傳遞的時候不小心畫到其中一本,所以那本就變你的,且別人無法拿到

這邊有幾個重點:

第一排往後傳遞,傳到最後一個(props)
別人無法拿到(state)

故事編得很爛,我知道...

State

以上面的例子來看state就是不能傳遞的部分,他只能在單一component內執行,不過如果你透過其他方式把它送出去,當然另當別論,不過單以state來說,他就是單一component的資料,寫法如下(function component需搭配hooks所以這邊先跳過):

class component

import "./styles.css";
import React from 'react'

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hello: 'hello'
    };
  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>{this.state.hello}, world!</h2> 
      </div>
    );
  }
}

export default Hello;

從上面的程式碼中,可以看出來我在state裡面塞了一個變數叫hello,然後回到頁面去使用它(this.state.hello),基本上state就是這樣:在component裡面去做宣告,然後只限當前component使用

Props

Props其實就跟傳遞書本是同樣的意思,都是可傳遞的部分,這邊直接上程式碼會比較容易了解

class Father extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hello: "hello"
    };
  }
  render() {
    return (
      <div>
        <h1>{this.state.hello}, Child</h1>
        <Child hello={this.state.hello} /> // 這邊把state傳遞到Child
      </div>
    );
  }
}

export default Father;
class Child extends React.Component {
  render() {
    return (
      <div>
        <h1>{this.props.hello}, Father</h1> // 用props接收Father傳遞過來的hello
      </div>
    );
  }
}

export default Child;

從程式碼我們可以看出來Props主要是上層傳過來的資料,所以以後看專案後就可以知道哪個是這個頁面原生的資料,那個是從上一層傳遞過來的了

那今天就講到這邊,我們明天見


上一篇
Day4 Jsx
下一篇
Day6 Class vs Function
系列文
30天學會React8
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
gior__ann
iT邦新手 2 級 ‧ 2021-09-10 16:31:38

期待大大更新喔~加油

我要留言

立即登入留言