react组件间如何传递参数
父子组件传参(Props)
父组件通过属性(props)向子组件传递数据。子组件通过props接收参数,React 的函数组件和类组件均可使用。
父组件传递参数:
<ChildComponent name="张三" age={25} />
子组件接收参数(函数组件):
function ChildComponent(props) {
return <div>{props.name}, {props.age}</div>;
}
子组件接收参数(类组件):
class ChildComponent extends React.Component {
render() {
return <div>{this.props.name}, {this.props.age}</div>;
}
}
子组件向父组件传参(回调函数)
父组件通过传递回调函数给子组件,子组件调用该函数并传递参数。
父组件定义回调:
function ParentComponent() {
const handleData = (data) => {
console.log("子组件传递的数据:", data);
};
return <ChildComponent onData={handleData} />;
}
子组件调用回调:
function ChildComponent({ onData }) {
const sendData = () => {
onData("来自子组件的数据");
};
return <button onClick={sendData}>传递数据</button>;
}
跨层级组件传参(Context)
通过 React 的 Context API 实现跨层级组件数据共享,避免逐层传递 props。
创建 Context:
const MyContext = React.createContext();
父组件提供数据:
function ParentComponent() {
return (
<MyContext.Provider value={{ user: "李四", id: 100 }}>
<ChildComponent />
</MyContext.Provider>
);
}
子组件消费数据(函数组件):
function ChildComponent() {
const context = React.useContext(MyContext);
return <div>{context.user}, {context.id}</div>;
}
子组件消费数据(类组件):
class ChildComponent extends React.Component {
static contextType = MyContext;
render() {
return <div>{this.context.user}, {this.context.id}</div>;
}
}
全局状态管理(Redux)
通过 Redux 实现全局状态管理,适合复杂应用的多组件数据共享。
安装 Redux:
npm install redux react-redux
创建 Store 和 Reducer:
import { createStore } from 'redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
Provider 包裹根组件:
import { Provider } from 'react-redux';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
组件中使用:
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+1</button>
<span>{count}</span>
</div>
);
}
事件总线(Event Emitter)
通过第三方库(如 events)实现非父子组件间通信,适用于简单场景。
安装库:
npm install events
创建事件总线:
import { EventEmitter } from 'events';
const eventBus = new EventEmitter();
组件 A 发送事件:
eventBus.emit("eventName", { data: "参数" });
组件 B 监听事件:

useEffect(() => {
eventBus.on("eventName", (data) => {
console.log("接收数据:", data);
});
return () => eventBus.off("eventName"); // 清除监听
}, []);






