React Props
Props 是傳遞給 React 元件的引數。
Props 透過 HTML 屬性傳遞給元件。
props
是 properties(屬性)的縮寫。
React Props
React Props 就像 JavaScript 中的函式引數和 HTML 中的屬性。
要將 props 傳遞給元件,請使用與 HTML 屬性相同的語法
示例
在 Car 元素中新增一個 "brand" 屬性
const myElement = <Car brand="Ford" />;
元件將引數作為 props
物件接收
傳遞資料
Props 也是如何將資料從一個元件傳遞到另一個元件(作為引數)的方式。
示例
將 Garage 元件中的 "brand" 屬性發送到 Car 元件
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
如果你要傳送的是一個變數,而不是像上面例子中的字串,只需將變數名放在花括號內即可
示例
建立一個名為 carName
的變數並將其傳送到 Car
元件
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
或者如果它是一個物件
示例
建立一個名為 carInfo
的物件並將其傳送到 Car
元件
function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
注意: React Props 是隻讀的!如果你試圖更改它們的值,將會收到錯誤。