react 如何传递props
传递 Props 的方法
在 React 中,Props(属性)是组件之间传递数据的主要方式。以下是几种常见的传递 Props 的方法:
父组件向子组件传递 Props
父组件通过在子组件标签上添加属性的方式传递数据。子组件通过 props 对象接收这些数据。
// 父组件
function ParentComponent() {
const message = "Hello from Parent";
return <ChildComponent greeting={message} />;
}
// 子组件
function ChildComponent(props) {
return <h1>{props.greeting}</h1>;
}
使用解构赋值简化 Props 接收
子组件可以通过解构赋值直接提取 props 中的属性,使代码更简洁。
function ChildComponent({ greeting }) {
return <h1>{greeting}</h1>;
}
传递多个 Props
可以一次性传递多个属性,子组件按需接收。

// 父组件
function ParentComponent() {
const user = { name: "Alice", age: 25 };
return <ChildComponent name={user.name} age={user.age} />;
}
// 子组件
function ChildComponent({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
通过展开运算符传递 Props
使用展开运算符可以批量传递对象的属性作为 Props。
const user = { name: "Bob", age: 30 };
return <ChildComponent {...user} />;
传递函数作为 Props
父组件可以将函数作为 Props 传递给子组件,实现子组件向父组件通信。

// 父组件
function ParentComponent() {
const handleClick = () => {
console.log("Button clicked in child");
};
return <ChildComponent onClick={handleClick} />;
}
// 子组件
function ChildComponent({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
默认 Props
可以为组件设置默认的 Props 值,防止未传递时出现未定义错误。
function ChildComponent({ greeting = "Default Greeting" }) {
return <h1>{greeting}</h1>;
}
Props 类型校验
使用 PropTypes 或 TypeScript 可以对 Props 进行类型检查,确保数据类型正确。
import PropTypes from 'prop-types';
function ChildComponent({ greeting }) {
return <h1>{greeting}</h1>;
}
ChildComponent.propTypes = {
greeting: PropTypes.string.isRequired
};
注意事项
- Props 是只读的,子组件不应直接修改接收到的 Props。
- 避免传递过多的 Props,必要时可以合并为对象传递。
- 对于深层嵌套的组件,考虑使用 Context API 或状态管理工具替代 Props 传递。






