React Props
Props 是传递给 React 组件的参数。
Props 通过 HTML 属性传递给组件。
Props 代表属性。React Props
React Props 类似于 JavaScript 中的 函数参数 和 HTML 中的 属性。
要将道具发送到组件中,请使用与 HTML 属性相同的语法:
实例
向 Car 元素添加一个 brand 属性:
const myelement = <Car brand="Ford" />;
组件将参数作为 props 对象接收:
实例
在组件中使用 brand 属性:
import React from 'react';import ReactDOM from 'react-dom';function Car(props) {return <h2>I am a { props.brand }!</h2>;}const myelement = <Car brand="Ford" />;ReactDOM.render(myelement, document.getElementById('root'));
传递数据
Props 也是将数据作为参数从一个组件传递到另一个组件的方式。
实例
将 brand 属性从 Garage 组件发送到 Car 组件中:
import React from 'react';import ReactDOM from 'react-dom';function Car(props) {return <h2>I am a { props.brand }!</h2>;}function Garage() {return (<><h1>Who lives in my garage?</h1><Car brand="Ford" /></>);}ReactDOM.render(<Garage />, document.getElementById('root'));
如果要发送一个变量,而不是上面示例中的字符串,则只需将变量名放在花括号内即可:
实例
创建一个名为 carName 的变量并将其发送到 Car 组件:
import React from 'react';import ReactDOM from 'react-dom';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 } /></>);}ReactDOM.render(<Garage />, document.getElementById('root'));
或者是一个对象:
实例
创建名为 carInfo 的对象并将其发送到 Car 组件:
import React from 'react';import ReactDOM from 'react-dom';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 } /></>);}ReactDOM.render(<Garage />, document.getElementById('root'));
注意:React Props 是只读的!如果试图更改它们的值,则会出现错误。