我正在尝试关闭一个弹出窗口,该弹出窗口只能通过其渲染 Prop 中的关闭回调来关闭。我想知道如何使用钩子(Hook)或其他策略在渲染之间保存此回调函数,以便在 useEffect 中调用它。我尝试使用 useContext 无济于事:https://codesandbox.io/s/popover-close-from-content-y637f
最佳答案
您可以使用 ref 来保存 close 函数以在 useEffect 中使用。这是一个工作代码和框:https://codesandbox.io/s/popover-close-from-content-sgmgs
import React, { useEffect, useState, useRef } from "react";
import { Block } from "baseui/block";
import { Button } from "baseui/button";
import { StatefulPopover } from "baseui/popover";
export default () => {
const closeRef = useRef();
const [state, setState] = useState({ isSaving: false });
useEffect(() => {
if (state.isSaving) {
const timeout = setTimeout(() => {
console.log("closing", closeRef.current);
// close popover from here
closeRef.current && closeRef.current();
setState({ isSaving: false });
}, 5000);
return () => {
clearTimeout(timeout);
};
}
}, [state.isSaving]);
const onSave = () => {
console.log("save btn clicked");
setState({ isSaving: true });
};
return (
<div>
<StatefulPopover
content={(
{ close } // I need to call close per this library's API to close
) => {
closeRef.current = close;
return (
<Block padding="scale500" maxWidth="300px">
<Block paddingBottom="scale400">
content render prop is passed a <code>close()</code> callback so
it you can manually trigger popover close from within
</Block>
<Button isLoading={state.isSaving} onClick={onSave}>
Save
</Button>
</Block>
);
}}
>
<Button>Click Me</Button>
</StatefulPopover>
</div>
);
};
上下文未按您预期的方式工作,因为您尝试使用提供程序外部的 useContext
访问上下文。为了从 Provider 访问值,必须在上下文 Provider 的子组件内部使用 useContext
Hook 。否则,useContext
只会获取传递给createContext
的默认值。
关于javascript - 如何使用渲染之间的钩子(Hook)从其父组件调用 render prop 提供的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56330960/