react组件如何通信
父子组件通信
父组件通过 props 向子组件传递数据,子组件通过回调函数(如 onChange)向父组件传递数据。
// 父组件
function Parent() {
const [value, setValue] = useState("");
return <Child value={value} onChange={(newValue) => setValue(newValue)} />;
}
// 子组件
function Child({ value, onChange }) {
return <input value={value} onChange={(e) => onChange(e.target.value)} />;
}
兄弟组件通信
通过 状态提升 将共享状态提升至共同的父组件,再通过 props 传递数据和方法。
function Parent() {
const [sharedData, setSharedData] = useState("");
return (
<>
<SiblingA data={sharedData} onUpdate={setSharedData} />
<SiblingB data={sharedData} />
</>
);
}
跨层级组件通信(Context API)
使用 React.createContext 和 useContext 实现跨层级数据传递,避免逐层传递 props。
const DataContext = React.createContext();
function App() {
const [data, setData] = useState("");
return (
<DataContext.Provider value={{ data, setData }}>
<ComponentA />
</DataContext.Provider>
);
}
function ComponentA() {
return <ComponentB />;
}
function ComponentB() {
const { data, setData } = useContext(DataContext);
return <input value={data} onChange={(e) => setData(e.target.value)} />;
}
全局状态管理(Redux / Zustand)
使用第三方库(如 Redux 或 Zustand)管理全局状态,适用于复杂应用。
Redux 示例:
// store.js
import { createStore } from "redux";
const reducer = (state = "", action) => {
switch (action.type) {
case "UPDATE_DATA":
return action.payload;
default:
return state;
}
};
const store = createStore(reducer);
// ComponentA.js
import { useDispatch } from "react-redux";
function ComponentA() {
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: "UPDATE_DATA", payload: "New Data" })}>
Update Data
</button>
);
}
// ComponentB.js
import { useSelector } from "react-redux";
function ComponentB() {
const data = useSelector((state) => state);
return <div>{data}</div>;
}
事件总线(Event Emitter)
通过自定义事件或第三方库(如 events)实现组件间通信,适用于非父子关系的组件。
import { EventEmitter } from "events";
const eventBus = new EventEmitter();
function ComponentA() {
const handleClick = () => {
eventBus.emit("customEvent", "Data from A");
};
return <button onClick={handleClick}>Send Event</button>;
}
function ComponentB() {
const [data, setData] = useState("");
useEffect(() => {
const handler = (payload) => setData(payload);
eventBus.on("customEvent", handler);
return () => eventBus.off("customEvent", handler);
}, []);
return <div>{data}</div>;
}
使用 Refs 直接访问组件
通过 useRef 或 forwardRef 直接调用子组件方法,适用于需要直接操作 DOM 或组件实例的场景。
const Child = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
}));
return <input ref={inputRef} />;
});
function Parent() {
const childRef = useRef();
return (
<>
<Child ref={childRef} />
<button onClick={() => childRef.current.focus()}>Focus Input</button>
</>
);
}






