react父子组件如何调用
父组件调用子组件方法
使用 useRef 和 forwardRef 结合暴露子组件方法。在子组件中使用 useImperativeHandle 定义可被父组件调用的方法。
父组件示例代码:
import { useRef } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.childMethod();
};
return (
<div>
<button onClick={handleClick}>调用子组件方法</button>
<ChildComponent ref={childRef} />
</div>
);
}
子组件示例代码:
import { forwardRef, useImperativeHandle } from 'react';
const ChildComponent = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
childMethod: () => {
console.log('子组件方法被调用');
}
}));
return <div>子组件</div>;
});
子组件调用父组件方法
通过 props 传递回调函数给子组件。子组件在需要时调用这个 props 方法。
父组件示例代码:
function ParentComponent() {
const parentMethod = () => {
console.log('父组件方法被调用');
};
return <ChildComponent onParentCall={parentMethod} />;
}
子组件示例代码:
function ChildComponent({ onParentCall }) {
const handleClick = () => {
onParentCall();
};
return <button onClick={handleClick}>调用父组件方法</button>;
}
使用 Context 跨层级通信
创建 Context 并共享状态和方法,适用于深层嵌套组件。
Context 示例代码:
import { createContext, useContext } from 'react';
const FamilyContext = createContext();
function ParentComponent() {
const sharedMethod = () => {
console.log('共享方法被调用');
};
return (
<FamilyContext.Provider value={{ sharedMethod }}>
<ChildComponent />
</FamilyContext.Provider>
);
}
function ChildComponent() {
const { sharedMethod } = useContext(FamilyContext);
return <button onClick={sharedMethod}>调用共享方法</button>;
}
使用自定义事件通信
通过自定义事件实现完全解耦的组件通信,适用于非父子关系的组件。
事件总线示例代码:

const events = {};
const eventBus = {
on(event, callback) {
if (!events[event]) events[event] = [];
events[event].push(callback);
},
emit(event, data) {
if (events[event]) {
events[event].forEach(callback => callback(data));
}
}
};
// 组件A
eventBus.on('customEvent', data => {
console.log('收到事件:', data);
});
// 组件B
eventBus.emit('customEvent', { message: 'Hello' });






