react 如何传递props
传递 Props 的基本方式
在 React 中,父组件可以通过属性(props)将数据传递给子组件。子组件通过函数参数或 this.props(类组件)接收这些数据。
// 父组件
function ParentComponent() {
const message = "Hello from parent";
return <ChildComponent greeting={message} />;
}
// 子组件(函数组件)
function ChildComponent(props) {
return <div>{props.greeting}</div>;
}
// 子组件(类组件)
class ChildComponent extends React.Component {
render() {
return <div>{this.props.greeting}</div>;
}
}
传递多个 Props
可以通过展开运算符一次性传递多个 props,避免逐一声明。

function ParentComponent() {
const user = { name: "Alice", age: 25 };
return <ChildComponent {...user} />;
}
默认 Props
为组件设置默认 props,防止未传递时出现未定义错误。
function ChildComponent(props) {
return <div>{props.greeting}</div>;
}
ChildComponent.defaultProps = {
greeting: "Default greeting"
};
Props 类型校验
使用 PropTypes 或 TypeScript 对 props 进行类型校验,确保数据符合预期。

import PropTypes from 'prop-types';
function ChildComponent(props) {
return <div>{props.greeting}</div>;
}
ChildComponent.propTypes = {
greeting: PropTypes.string.isRequired
};
传递函数作为 Props
可以将函数作为 props 传递给子组件,实现父子组件通信。
function ParentComponent() {
const handleClick = () => alert("Button clicked");
return <ChildComponent onClick={handleClick} />;
}
function ChildComponent(props) {
return <button onClick={props.onClick}>Click me</button>;
}
通过 Children Prop 传递内容
通过 children prop 可以直接在组件标签内传递内容(如文本、元素或其他组件)。
function ParentComponent() {
return <ChildComponent>This is children content</ChildComponent>;
}
function ChildComponent(props) {
return <div>{props.children}</div>;
}






