react父子组件如何通信
父组件向子组件传递数据
通过props传递数据是最常见的方式。父组件可以在子组件标签上定义属性,子组件通过props接收。
父组件示例:
import ChildComponent from './ChildComponent';
function ParentComponent() {
const data = "Hello from parent";
return <ChildComponent message={data} />;
}
子组件示例:
function ChildComponent(props) {
return <div>{props.message}</div>;
}
子组件向父组件传递数据
通过回调函数实现。父组件传递一个函数给子组件,子组件调用该函数并传递数据。
父组件示例:
function ParentComponent() {
const handleData = (data) => {
console.log(data);
};
return <ChildComponent onData={handleData} />;
}
子组件示例:
function ChildComponent({ onData }) {
const sendData = () => {
onData("Data from child");
};
return <button onClick={sendData}>Send</button>;
}
使用Context跨层级通信
当组件层级较深时,可以使用React Context避免props逐层传递。
创建Context:
const MyContext = React.createContext();
function App() {
return (
<MyContext.Provider value="Shared data">
<ParentComponent />
</MyContext.Provider>
);
}
子组件消费Context:
function ChildComponent() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
使用Ref访问子组件实例
父组件可以通过ref直接调用子组件的方法或访问其状态。
父组件示例:
function ParentComponent() {
const childRef = useRef();
const callChildMethod = () => {
childRef.current.childMethod();
};
return (
<>
<ChildComponent ref={childRef} />
<button onClick={callChildMethod}>Call Child</button>
</>
);
}
子组件示例:

const ChildComponent = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
childMethod: () => {
console.log("Child method called");
}
}));
return <div>Child Component</div>;
});
使用状态管理库
对于复杂应用,可以使用Redux、MobX或Recoil等状态管理库,实现组件间的数据共享和通信。这些库提供了集中式的状态管理,任何组件都可以订阅和修改共享状态。






