简体   繁体   English

如何在 React 中创建可重复使用的弹出框

[英]How to create a re-usable popup box in React

I'm pretty stuck here and there's a good chance I'm going about this all wrong.我被困在这里了,我很有可能把这一切都搞错了。 I'm trying to create an options menu using a series of popup boxes.我正在尝试使用一系列弹出框创建一个选项菜单。 Basically, the user clicks on the box, some kind of dialog pops up and they either input something or choose something based on the option in question.基本上,用户单击该框,会弹出某种对话框,他们要么输入某些内容,要么根据相关选项选择某些内容。

I have the logic for clicking and showing popups separated out into another component, ClickablePopup , which allows me to not repeat the logic for opening and closing the popup.我有用于单击和显示分离到另一个组件ClickablePopup的弹出窗口的逻辑,这允许我不重复打开和关闭弹出窗口的逻辑。 But I am really not sure how to cause the popup to close based on a signal from the children , which I intend to be able to contain several different kinds of inputs.但我真的不确定如何根据来自children的信号关闭弹出窗口,我打算能够包含几种不同类型的输入。

The ClickablePopup component I've been trying to use:我一直在尝试使用的 ClickablePopup 组件:

const ClickablePopup = ({ children, label }) => {
  const [openPopup, setOpenPopup] = useState(false);

  const togglePopup = () => {
    setOpenPopup(!openPopup);
  };

  const ref = useDetectClickOutside({
    onTriggered: () => {
      if (openPopup) {
        setOpenPopup(false);
      }
    }
  });

  return (
    <div ref={ref}>
      {openPopup ? (
        <>{children}</>
      ) : (
        <div className="badge" onClick={() => togglePopup()}>
          {label}
        </div>
      )}
    </div>
  );
};

Here is a codesandbox with what I have so far: https://codesandbox.io/s/cra-g8215s?file=/App.js这是我到目前为止所拥有的代码框: https://codesandbox.io/s/cra-g8215s?file=/App.js

As mentioned, I'm pretty well stuck because I just can't think of how to get the inside "wrapped" component to send a signal to its wrapper.如前所述,我很困惑,因为我只是想不出如何让内部“包装”组件向其包装器发送信号。

you can add togglePopup to child ref and use it in parent您可以将 togglePopup 添加到子引用并在父引用中使用它

https://pl.reactjs.org/docs/hooks-reference.html#useimperativehandle https://pl.reactjs.org/docs/hooks-reference.html#useimperativehandle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM