【发布时间】:2021-11-05 18:08:56
【问题描述】:
我正在尝试从显示加载覆盖的父组件调用子组件中的方法。我正在使用 refs 来调用子方法。但是当我在渲染函数之前调用子方法时,ref.current 正在返回 undefined。
我关注了这个问题: userRef or createRef returning undefined in functional component
我确实在 useEffect 中添加了 ref.current,但没有任何区别。我的代码如下:
const ParentComponent = ({ actions,...props}) => {
const activeListPageRef = useRef();
useEffect(()=>{
console.log(activeListPageRef.current);
});
const getResources = async(resourceIds) => {
console.log("activeList ref", activeListPageRef);
if(activeListPageRef.current) {
activeListPageRef.current.onBtShowLoading();
}
//fetch api
//once done fetching on success hide the loading overlay
activeListPageRef.current.onBTHide();
}
return (
< childComponent ref={activeListPageRef} />
)
}
const ChildComponent =({ tableData, ...props}, ref) => {
const onBtShowLoading = () => {
gridApi.showLoadingOverlay();
};
}
useImperativeHandle(ref, () => ({
onGridReady,
onBtShowLoading,
onBtHide
}));
如何在调用子组件之前引用子组件方法?
【问题讨论】:
标签: reactjs