Menu
×
   ❮     
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 属性


属性是传递给 React 组件的参数。

属性通过 HTML 属性传递给组件。

props 代表属性。


React 属性

React 属性类似于 JavaScript 中的函数参数 *以及* HTML 中的属性。

要将属性发送到组件,请使用与 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 报名

传递数据

属性也是将数据从一个组件传递到另一个组件(作为参数)的方式。

示例

从 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 属性是只读的!如果您尝试更改其值,将会出现错误。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.