react组件如何通信
React 组件通信方法
父子组件通信(Props)
父组件通过 props 向子组件传递数据,子组件通过回调函数将数据传回父组件。
// 父组件
function Parent() {
const [data, setData] = useState("Hello");
const handleChildData = (childData) => {
setData(childData);
};
return <Child data={data} onChildData={handleChildData} />;
}
// 子组件
function Child({ data, onChildData }) {
return (
<button onClick={() => onChildData("World")}>
{data}
</button>
);
}
子父组件通信(回调函数)
子组件通过父组件传递的回调函数将数据传回父组件,如上例中的 onChildData。
兄弟组件通信(状态提升)
将共享状态提升到最近的共同父组件中,通过 props 传递给兄弟组件。

function Parent() {
const [sharedData, setSharedData] = useState("Shared");
return (
<>
<SiblingA data={sharedData} />
<SiblingB onDataChange={setSharedData} />
</>
);
}
跨层级通信(Context API)
使用 React.createContext 和 useContext 实现跨层级组件通信。
const DataContext = React.createContext();
function App() {
const [data, setData] = useState("Context Data");
return (
<DataContext.Provider value={{ data, setData }}>
<ComponentA />
</DataContext.Provider>
);
}
function ComponentA() {
return <ComponentB />;
}
function ComponentB() {
const { data, setData } = useContext(DataContext);
return <button onClick={() => setData("Updated")}>{data}</button>;
}
全局状态管理(Redux/Zustand)
使用第三方状态管理库(如 Redux 或 Zustand)实现复杂应用的全局状态共享。

// Redux 示例
import { createSlice, configureStore } from "@reduxjs/toolkit";
const dataSlice = createSlice({
name: "data",
initialState: { value: "Redux Data" },
reducers: {
update: (state, action) => {
state.value = action.payload;
},
},
});
const store = configureStore({ reducer: dataSlice.reducer });
function Component() {
const data = useSelector((state) => state.data.value);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(dataSlice.actions.update("New Data"))}>
{data}
</button>
);
}
事件总线(Event Emitter)
通过自定义事件系统实现任意组件间通信(适用于非 React 生态的集成场景)。
const events = new EventEmitter();
function ComponentA() {
useEffect(() => {
events.emit("event", "Event Data");
}, []);
}
function ComponentB() {
const [data, setData] = useState("");
useEffect(() => {
events.on("event", setData);
return () => events.off("event", setData);
}, []);
return <div>{data}</div>;
}
Refs 和 DOM 操作
通过 useRef 直接访问组件实例或 DOM 节点(慎用,破坏 React 数据流)。
function Parent() {
const childRef = useRef();
const handleClick = () => {
childRef.current.doSomething();
};
return (
<>
<Child ref={childRef} />
<button onClick={handleClick}>Call Child</button>
</>
);
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
doSomething: () => console.log("Child Method"),
}));
return <div>Child</div>;
});






