菜单
×
   ❮     
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 提供支持