Sitemap
Zoe Peng

Zoe Peng

React — Props

4 min readAug 6, 2023

--

在加拿大軟體業市場摸索一陣子之後,發現當地非常少純前端的工作機會,大多都是全端工程師的職位,但實際上做的事情又幾乎會根據每間公司的不同稍微有所差異;我自己是非常不喜歡所謂的全端,特別是稍有規模的公司如果還這樣分,就是對軟體業的專業不尊重(話講得真重)。

最近自己經歷了 2023 年的北美軟體業大洗牌,遇上了不少摧殘,但也認識了不少相同領域的朋友,他們剛好都偏後端工程師,蠻常一起去咖啡廳幫他們解決前端方面的問題,就順便把他們有提過的問題記錄下來成這一篇篇的文章,也當作對自己以往的工作再複習了一次。

Get Zoe Peng’s stories in your inbox

Join Medium for free to get updates from this writer.

在 JavaScript 的世界裡,function 要接收一個 parameter 可以這麼帶:

function getProfilePic(username) {
return "https://photo.fb.com/" + username
}

function getProfileLink(username) {
return "https://www.fb.com/" + username
}

function getAvatarInfo(username) {
return {
pic: getProfilePic(username),
link: getProfileLink(username),
}
}

getAvatarInfo("zooeypeng")

因為 React 本身就是 JavaScript 的 function ,所以我們可以把同樣的概念套用在一起:

Component 的 Props 等於 Function 的 Parameters

如何傳值進去一個 Component

Props 就像是 Component 的屬性、武器,至於要怎麼讓這個 Component 裝載武器呢?就像上次在 JSX 文章提到的一樣,React 將這件事變得非常 HTML 化:

<img src='' /> // 這是 HTML

<Hello name='Zoe' /> // 這是 JSX

上面範例裡的 name 就是我們給 <Hello /> 這個 Component 的武器,而且其實我們可以給一個 Component 裝很多的武器:

<Profile
username="zooeypeng"
authed={true}
logout={handleLogout}
header={<h1>👋</h1>}
/>

值得注意的是:除了 string 之外,我們都需要再用中括號 {} 去表示這是 JavaScript 的魔法世界囉!同樣的規則下,我們也可以傳進一整個 object 當作這個 Component 的武器:

<DatePicker settings={{
format: "yy-mm-dd",
animate: false,
days: "abbreviate"
}} />

上面的例子提到了一個 boolean 屬性,這邊可以注意一下若要傳進去的為 true 的話可以這麼寫:

<Profile authed={true} />
<Profile authed />
// 這兩個是一樣的意思喔

如何從 Props 接收值

非常簡單的就是從 Props 裡拿出來:

function Hello (props) {
return <h1>Hello, {props.name}</h1>
}

export default function App () {
return <Hello name='Zoe' />
}

當有很多個的時候,也可以先解構好再拿出來:

function Hello ({ first, last }) {
return (
<h1>
Hello, {first} {last}
</h1>
)
}

又或著我們可以透過用 children 的方式拿:

function Layout (props) {
return (
<div className="layout">
<SideBar />
{props.children} // React 的保留字 { children }
<Footer />
</div>
)
}

<Layout>
<Pizza />
</Laylout>

總結

我真的是寫了一篇爛文章,要好好把 Props 講出個所以然實在是有點難度啊!

--

--