react组件间如何传递参数
通过 props 传递参数
父组件通过属性(props)向子组件传递数据。子组件通过 this.props(类组件)或直接解构 props(函数组件)接收参数。
// 父组件
<ChildComponent name="John" age={25} />
// 子组件(类组件)
class ChildComponent extends React.Component {
render() {
return <div>{this.props.name}, {this.props.age}</div>;
}
}
// 子组件(函数组件)
function ChildComponent({ name, age }) {
return <div>{name}, {age}</div>;
}
使用 Context API 跨层级传递
通过 React.createContext 创建上下文,父组件用 Provider 提供数据,子组件用 Consumer 或 useContext 钩子获取数据。
// 创建上下文
const MyContext = React.createContext();
// 父组件提供数据
<MyContext.Provider value={{ user: "Alice", id: 1 }}>
<ChildComponent />
</MyContext.Provider>
// 子组件消费数据(类组件)
class ChildComponent extends React.Component {
render() {
return (
<MyContext.Consumer>
{value => <div>{value.user}</div>}
</MyContext.Consumer>
);
}
}
// 子组件消费数据(函数组件)
function ChildComponent() {
const value = useContext(MyContext);
return <div>{value.user}</div>;
}
通过回调函数传递数据
子组件通过父组件传递的回调函数,将数据回传给父组件。
// 父组件
function ParentComponent() {
const handleData = (data) => {
console.log(data);
};
return <ChildComponent onData={handleData} />;
}
// 子组件
function ChildComponent({ onData }) {
const sendData = () => {
onData("Hello from child");
};
return <button onClick={sendData}>Send</button>;
}
使用状态管理库(如 Redux)
通过全局状态管理实现任意组件间的数据共享。
// 定义 action 和 reducer
const setUser = (user) => ({ type: 'SET_USER', payload: user });
function userReducer(state = null, action) {
switch (action.type) {
case 'SET_USER': return action.payload;
default: return state;
}
}
// 组件中调用
import { useDispatch, useSelector } from 'react-redux';
function ComponentA() {
const dispatch = useDispatch();
dispatch(setUser("Bob"));
}
function ComponentB() {
const user = useSelector(state => state.user);
return <div>{user}</div>;
}
通过 ref 传递数据或方法
使用 React.forwardRef 实现 ref 转发,直接调用子组件方法或访问实例。
// 子组件(函数组件需用 forwardRef)
const ChildComponent = React.forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
showAlert: () => alert("Child method called")
}));
return <div>Child</div>;
});
// 父组件使用
function ParentComponent() {
const childRef = useRef();
const callChildMethod = () => {
childRef.current.showAlert();
};
return (
<>
<ChildComponent ref={childRef} />
<button onClick={callChildMethod}>Call</button>
</>
);
}






