react 如何传递props
传递 props 的基本方法
在 React 中,props 是从父组件向子组件传递数据的主要方式。通过在子组件的标签上添加属性,可以将数据传递给子组件。
父组件中传递 props:
function ParentComponent() {
const message = "Hello from parent";
return <ChildComponent greeting={message} />;
}
子组件中接收 props:
function ChildComponent(props) {
return <div>{props.greeting}</div>;
}
使用解构赋值简化 props
可以直接在子组件参数中解构 props,使代码更简洁:

function ChildComponent({ greeting }) {
return <div>{greeting}</div>;
}
传递多个 props
可以一次传递多个 props:
function ParentComponent() {
const user = {
name: "Alice",
age: 25
};
return <UserProfile {...user} />;
}
子组件接收多个 props:
function UserProfile({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
传递函数作为 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,当父组件未传递相应 prop 时使用默认值:
function Greeting({ name }) {
return <div>Hello, {name}!</div>;
}
Greeting.defaultProps = {
name: "Guest"
};
使用 prop-types 进行类型检查
可以安装 prop-types 库来验证 props 的类型:
import PropTypes from 'prop-types';
function Product({ name, price }) {
return (
<div>
<h3>{name}</h3>
<p>Price: ${price}</p>
</div>
);
}
Product.propTypes = {
name: PropTypes.string.isRequired,
price: PropTypes.number.isRequired
};
特殊 props:children
children 是一个特殊 prop,表示组件标签之间的内容:
function Card({ children }) {
return <div className="card">{children}</div>;
}
function App() {
return (
<Card>
<h2>Card Title</h2>
<p>Card content goes here</p>
</Card>
);
}






