ReactJS入門 - Props 綁定資料與函式
Props 是做什麼的
Props 是 React 中用來傳遞元件屬性(attribute)的物件,例如:
<button value="886">886</button>
props 當中會包含了這個元件的屬性,例如這個按鈕的 value 、文字等,在 React 會被包成像是這樣的物件
{
value: "886"
}
當然,你可以自訂自己元件的屬性並傳遞,下面就會說到這個部分
使用 props 綁定資料
這篇文章主要會以 functional component 來示範,如果要使用在 class component 的部分,我會放在最後面,基本上差不多。
首先打開 index.js,修改 ReactDOM.render 的函式:
ReactDOM.render( <> <App name="哈囉你好嗎"></App> </> , document.getElementById('root') );
再打開 App.js ,將 props 這個參數帶到 function
function App(props) { }
再把 function 裡面的內容換成這樣:
function App(props) { return( <h1> { props.name } </h1> ); }
然後執行之後就會有一個大大的”哈囉你好嗎”顯示在網頁上。
注意傳遞方式(資料型態)
還記得在 JSX 提過的大括號嗎?如果你在傳遞屬性的時候沒有用大括號而是用過去寫 html 的習慣的話,例如:
<App num="87" data="true"/>
這樣傳進 App 裡之後都會是字串型態,如果要型態正確必須使用大括號:
<App num={87} data={true}/>
這樣才會在 App 當中得到正確的資料型態(整數與布林)。
上一篇文章我們有提過有兩種情況會導致重新渲染畫面,其中一個就是 props 的改變,第二個 state 會在後面的篇章介紹。
props 是唯讀(Read-only)的
將屬性以 props 傳入 App 之後是不能被更改的,如果嘗試在 App 這樣做是錯誤的:
props.name = "我不好啦!!"
如果要更改 props 的值,之後也會有篇章提到要如何做。
使用 props 綁定函式
除了綁定資料以外, props 本身也能綁定函式,例如今天在 index.js 有一個 function 叫做 showAlert ,用來顯示訊息視窗:
const showAlert = ()=>{ alert("show"); }
今天在把他綁到 App 這個元件上面去:
然後到 App.js 增加一個按鈕並綁定 onClick 事件:
function App(props) {
return(
<div> <h1> { props.name } </h1>
<button onClick={ props.show }>Show~~</button> </div>
);
}
再執行之後按一下按鈕就會執行綁定在上面的函式,跳出訊息視窗。
要注意,在呼叫使用 props 的時候,要使用綁定的名稱,而非原本的名稱(除非名稱一樣)。例如原本 index.js 的函式叫做 showAlert,但是綁到 App 上的叫做 show,所以在 App.js 使用的時候是要用 props.show 而非 props.showAlrrt。
props.children
我們在 index.js 當中的 App 元件中間沒有加入任何東西,先試著加加看,改成這樣:
ReactDOM.render(
<>
<App name="哈囉你好嗎" show={ showAlert }>這是 index.js </App>
</>
,
document.getElementById('root')
);
然後把 App.js 的 function修改成:
function App(props) {
return(
<div> <h1> { props.children } </h1>
<button onClick={ props.show }>Show~~</button> </div>
);
}
你會看到我們夾在 index.js 中的 <App></App> 裡面的東西,而這夾在中間的東西也會連同 props 一起綁定,稱為 children。
在日後專案逐漸增大,通常會出現必須要用多個元件才能組成完整的網頁,例如切成導航以及內容兩個元件:
所以我們以這個當作範例,新增一個 NavBar.js,然後篩寫以下內容:
import React, { Component } from 'react';
const styleSheet = {
position:"fixed",
top:"0",
left:"0",
width:"100%",
height:"43px",
backgroundColor:"blue",
display:"flex",
alignItems:"center",
color: "white"
}
const contentStyle = {
marginTop: "50px"
}
const NavBar = (props)=> {
return(
<>
<div style={ styleSheet } className="nav">
<a>Home</a>
|
<a>produnt</a>
</div>
<div style={ contentStyle } className="content">
{ props.children }
</div>
</>
)
}
export default NavBar;
然後修改一下 index.js,先 import NavBar,並使用它:
import NavBar from './NavBar';
ReactDOM.render(
<>
<NavBar>
<App name="哈囉你好嗎" show={ showAlert }>這是 index.js </App>
</NavBar>
</>
,
document.getElementById('root')
);
然後就可以看到下面的效果了
結論
基本上 class component 以及 functional component 的 props 使用起來都大同小異, props 在做父對子元件的資料傳輸相當重要。接下來將會先介紹 class component 的部分 — state 與 setState,當然在之後也會介紹 functional component 的 state,那邊會放到 React Hook 的部分介紹。
Originally published at https://studio-44s.tw.