react组件如何传递参数
传递 props 给子组件
在父组件中通过属性名直接传递数据,子组件通过 props 对象接收。例如父组件传递 name 和 age:
<ChildComponent name="Alice" age={25} />
子组件通过解构或直接访问 props 使用:
function ChildComponent(props) {
return <div>{props.name} is {props.age} years old</div>;
}
// 或解构
function ChildComponent({ name, age }) {
return <div>{name} is {age} years old</div>;
}
动态传递 props
通过变量或表达式动态传递值。例如从父组件状态传递数据:

function ParentComponent() {
const [user, setUser] = useState({ name: "Bob", age: 30 });
return <ChildComponent name={user.name} age={user.age} />;
}
传递整个对象
使用展开运算符批量传递对象的属性:
const user = { name: "Charlie", age: 35 };
<ChildComponent {...user} />
传递函数
将父组件的函数作为回调传递给子组件:

function ParentComponent() {
const handleClick = () => console.log("Clicked");
return <ChildComponent onClick={handleClick} />;
}
function ChildComponent({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
使用 Context 跨层级传递
通过 React Context 实现深层组件参数传递:
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value={{ name: "Dave", age: 40 }}>
<DeepChildComponent />
</UserContext.Provider>
);
}
function DeepChildComponent() {
const user = useContext(UserContext);
return <div>{user.name}</div>;
}
通过 children 传递内容
使用 props.children 传递组件之间的嵌套内容:
function ParentComponent() {
return (
<ChildComponent>
<div>This content is passed as children</div>
</ChildComponent>
);
}
function ChildComponent({ children }) {
return <div className="container">{children}</div>;
}
使用 Render Props 模式
通过函数 prop 共享组件间的代码:
function MouseTracker(props) {
const [position, setPosition] = useState({ x: 0, y: 0 });
return props.render(position);
}
function App() {
return (
<MouseTracker render={({ x, y }) => (
<div>Mouse at ({x}, {y})</div>
)} />
);
}






