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 是只读的!如果你试图更改它们的值,将会收到错误。