react如何调用子组件的函数
调用子组件函数的常见方法
使用 ref 直接调用
通过 React.createRef() 或 useRef 创建引用,附加到子组件上。子组件需用 forwardRef 暴露内部方法,类组件则直接通过 ref.current 访问实例方法。

// 父组件
const Parent = () => {
const childRef = useRef();
const handleClick = () => childRef.current.childMethod();
return <Child ref={childRef} />;
};
// 子组件(函数组件)
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
childMethod: () => console.log('方法被调用')
}));
return <div>子组件</div>;
});
通过 Props 传递回调 父组件将函数作为 prop 传递给子组件,子组件在适当时机调用该函数实现通信。

// 父组件
const Parent = () => {
const handleChildCall = () => console.log('子组件触发');
return <Child onAction={handleChildCall} />;
};
// 子组件
const Child = ({ onAction }) => {
return <button onClick={onAction}>触发父组件</button>;
};
使用 Context 跨层级通信 通过 React Context 在任意层级组件间共享方法和状态,适用于深层嵌套场景。
const ChildContext = createContext();
const Parent = () => {
const [action, setAction] = useState();
return (
<ChildContext.Provider value={{ triggerAction: () => setAction('触发') }}>
<Child />
</ChildContext.Provider>
);
};
事件总线或状态管理 对于复杂场景,可通过 Redux、MobX 或自定义事件总线实现组件间通信,解耦调用关系。
方法选择建议
- 直接父子关系优先使用
ref或 props 回调 - 深层嵌套组件考虑 Context 或状态管理工具
- 避免过度使用
ref破坏 React 数据流原则






