Props(Properties 的縮寫)是 React 中用于組件間通信的核心機制。它們允許數據從父組件單向傳遞到子組件。Props 是 React 組件不可變(只讀)的輸入參數,這種特性使得組件更加可預測且易于維護。
Props 的核心特性
單向數據流:Props 只能從父組件傳遞到子組件,不能反向傳遞
只讀性:接收組件不能修改傳入的 props
動態性:Props 使組件能夠根據傳入數據呈現不同內容
類型安全:結合 PropTypes 或 TypeScript 可以確保 props 類型正確
在 React 中使用 Props 的方法
1. 將 Props 傳遞給功能組件 功能組件通過參數接收 props
對象:
function Welcome(props) { ? return <h1>Hello, {props.name}</h1>; } // 使用組件 <Welcome name="Alice" />
2. 在功能組件中使用解構 解構賦值使代碼更簡潔:
function Welcome({ name }) { ? return <h1>Hello, {name}</h1>; } // 使用組件 <Welcome name="Bob" />
3. 傳遞多個 props 可以同時傳遞多個屬性:
function UserProfile({ name, age, location }) { ? return ( ? ? <div> ? ? ? <h2>{name}</h2> ? ? ? <p>Age: {age}</p> ? ? ? <p>Location: {location}</p> ? ? </div> ? ); } // 使用組件 <UserProfile name="Charlie" age={28} location="New York" />
4. 設置默認 Props 為 props 提供默認值:
function Greeting({ name = 'Guest' }) { ? return <p>Welcome, {name}!</p>; }
5. 將 Props 傳遞給類組件 類組件通過 this.props 訪問 props:
class Welcome extends React.Component { ? render() { ? ? return <h1>Hello, {this.props.name}</h1>; ? } } // 使用組件 <Welcome name="David" />
6. 傳遞子元素 (children) 通過 props.children 傳遞組件內容:
function Card({ children }) { ? return <div className="card">{children}</div>; } // 使用組件 <Card> ? <h3>Title</h3> ? <p>Content goes here</p> </Card>
Props 驗證 使用 PropTypes 或 TypeScript 驗證 props 類型:
import PropTypes from 'prop-types'; function User({ name, age }) { ? // 組件實現 } User.propTypes = { ? name: PropTypes.string.isRequired, ? age: PropTypes.number }; User.defaultProps = { ? age: 18 };