javascript - 如何使用渲染之间的钩子(Hook)从其父组件调用 render prop 提供的回调

标签 javascript reactjs

我正在尝试关闭一个弹出窗口,该弹出窗口只能通过其渲染 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/

相关文章:

javascript - Var status 不会计算为 js 上的数组

c# - 将 javascript 更新限制为仅 asp :UpdatePanel

reactjs - 类型 'string' 不可分配给类型 '"inherit"| "initial"| "unset"| "fixed"| "absolute"| "static"| "relative"| "sticky"'

reactjs - Material-UI ThemeProvider 没有将主题传递给组件

javascript - 使用 && 运算符的 jsx 语法错误

javascript - body 对焦不起作用

javascript - 如何修复错误行覆盖 bar c3 js

javascript - 如何从传单 map 中删除多个标记并添加新标记?

javascript - react : How to use setState inside functional component?

javascript - 如何将分组的 TextField 值设置为状态?