選單
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

React Props


Props 是傳遞給 React 元件的引數。

Props 透過 HTML 屬性傳遞給元件。

props 是 properties(屬性)的縮寫。


React Props

React Props 就像 JavaScript 中的函式引數 HTML 中的屬性。

要將 props 傳遞給元件,請使用與 HTML 屬性相同的語法

示例

在 Car 元素中新增一個 "brand" 屬性

const myElement = <Car brand="Ford" />;

元件將引數作為 props 物件接收

示例

在元件中使用 brand 屬性

function Car(props) {
  return <h2>I am a { props.brand }!</h2>;
}

執行示例 »


w3schools CERTIFIED . 2022

獲得認證!

完成 React 模組,完成練習,參加考試,並獲得 w3schools 認證!

$95 註冊

傳遞資料

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 是隻讀的!如果你試圖更改它們的值,將會收到錯誤。



×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援