react参数如何传递
参数传递方式
React 中参数传递主要有以下几种方式:
Props 传递
父组件通过属性(props)向子组件传递数据。子组件通过 props 对象接收参数。
// 父组件
<ChildComponent name="John" age={25} />
// 子组件
function ChildComponent(props) {
return <div>{props.name} - {props.age}</div>;
}
Context API
跨层级组件传递数据,避免逐层传递 props。

// 创建 Context
const UserContext = React.createContext();
// 提供数据
<UserContext.Provider value={{ name: "John", age: 25 }}>
<ChildComponent />
</UserContext.Provider>
// 子组件消费数据
function ChildComponent() {
const user = useContext(UserContext);
return <div>{user.name} - {user.age}</div>;
}
回调函数传递
父组件通过 props 传递回调函数,子组件调用时传参。
// 父组件
function ParentComponent() {
const handleUpdate = (data) => {
console.log(data);
};
return <ChildComponent onUpdate={handleUpdate} />;
}
// 子组件
function ChildComponent({ onUpdate }) {
return <button onClick={() => onUpdate("New Data")}>Submit</button>;
}
状态管理工具(如 Redux)
全局状态管理,通过 dispatch 和 selector 传递参数。

// 发送数据
dispatch({ type: 'UPDATE_DATA', payload: "New Data" });
// 接收数据
const data = useSelector(state => state.data);
动态路由参数
通过路由库(如 React Router)传递 URL 参数。
// 路由配置
<Route path="/user/:id" component={UserPage} />
// 组件获取参数
function UserPage({ match }) {
const { id } = match.params;
return <div>User ID: {id}</div>;
}
组件间直接引用(不推荐)
通过 ref 直接调用子组件方法并传参,但会破坏组件封装性。
// 父组件
const childRef = useRef();
childRef.current.updateData("New Data");
// 子组件
useImperativeHandle(ref, () => ({
updateData: (data) => { /* 处理数据 */ }
}));






