react如何实现组件通信
父组件向子组件通信(Props)
父组件通过props将数据传递给子组件。子组件通过this.props(类组件)或直接解构props(函数组件)接收数据。
// 父组件
function Parent() {
const message = "Hello from Parent";
return <Child message={message} />;
}
// 子组件
function Child({ message }) {
return <div>{message}</div>;
}
子组件向父组件通信(回调函数)
父组件通过props传递回调函数给子组件,子组件调用该函数将数据传回父组件。
// 父组件
function Parent() {
const handleData = (data) => {
console.log(data);
};
return <Child onData={handleData} />;
}
// 子组件
function Child({ onData }) {
const sendData = () => {
onData("Data from Child");
};
return <button onClick={sendData}>Send Data</button>;
}
兄弟组件通信(状态提升)
将共享状态提升到最近的共同父组件中,通过props传递数据和回调函数实现兄弟组件通信。

function Parent() {
const [sharedData, setSharedData] = useState("");
return (
<>
<SiblingA onData={setSharedData} />
<SiblingB data={sharedData} />
</>
);
}
function SiblingA({ onData }) {
return <button onClick={() => onData("Data from A")}>Send to B</button>;
}
function SiblingB({ data }) {
return <div>Received: {data}</div>;
}
Context API跨层级通信
使用React的Context API可以在组件树中跨层级传递数据,避免props层层传递。
const MyContext = React.createContext();
function App() {
return (
<MyContext.Provider value="Global Data">
<ComponentA />
</MyContext.Provider>
);
}
function ComponentA() {
return <ComponentB />;
}
function ComponentB() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
使用状态管理库(Redux/MobX)
对于大型应用,可以使用Redux或MobX等状态管理库集中管理应用状态,实现任意组件间的通信。

// Redux示例
import { useSelector, useDispatch } from 'react-redux';
function ComponentA() {
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: 'UPDATE', payload: 'New Data' })}>
Update Store
</button>
);
}
function ComponentB() {
const data = useSelector(state => state.data);
return <div>{data}</div>;
}
使用自定义事件(Event Emitter)
通过事件发布订阅模式实现组件通信,适用于非父子关系的组件。
import { EventEmitter } from 'events';
const emitter = new EventEmitter();
function ComponentA() {
const emitEvent = () => {
emitter.emit('customEvent', 'Event Data');
};
return <button onClick={emitEvent}>Emit Event</button>;
}
function ComponentB() {
const [data, setData] = useState('');
useEffect(() => {
const handler = (data) => setData(data);
emitter.on('customEvent', handler);
return () => emitter.off('customEvent', handler);
}, []);
return <div>Received: {data}</div>;
}
使用Refs
通过ref直接访问组件实例或DOM元素,适用于需要直接操作子组件的场景。
function Parent() {
const childRef = useRef();
const callChildMethod = () => {
childRef.current.doSomething();
};
return (
<>
<Child ref={childRef} />
<button onClick={callChildMethod}>Call Child Method</button>
</>
);
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
doSomething: () => console.log('Child method called')
}));
return <div>Child Component</div>;
});






