如何在动态子按钮上附加关闭功能?

Posted

技术标签:

【中文标题】如何在动态子按钮上附加关闭功能?【英文标题】:How to attach close function on dyanmic children button? 【发布时间】:2021-11-13 10:12:33 【问题描述】:

我有一个 Tooltip 组件,它是动态内容的包装器。

我正在尝试将其用作弹出窗口,其中包含删除和取消按钮。

我将删除和取消按钮作为子属性传递,问题是 cus 关闭和打开状态在 Tooltip 组件中。

我需要在 Children 属性中的 Cancel 按钮上附加关闭功能。

需要帮助才能找到一个优雅的解决方案。

工具提示组件:


export const Tooltip: FC<TooltipProps> = (
  content,
  helperText,
  children,
  ...props
) => 
  const [visible, setVisible] = useState(false);

  const show = () => setVisible(true);
  const hide = () => setVisible(false);

  return (
    <div>
      <Tippy
        content=content
        visible=visible
        onClickOutside=hide
        interactive
        ...props
      >
        <div onClick=visible ? hide : show>
        
          // =====>>> **Close button which be in children prop, need to attach hide() function**
          children

        </div>
      </Tippy>
    </div>
  );
;

这是 Tooltip 组件的调用并将按钮作为子项传递:


 

 <Tooltip
     content=
       <div className="popover-buttons">
          
          // Need to attach here **hide()** function from Tooltip coomponent
          <button>
              Cancel
          </button>
          
           <button>
              Delete
           </button>
        </div>
 </Tooltip>

【问题讨论】:

【参考方案1】:

您可以将传递给Tippy 的内容道具设为一个组件,该组件将hide() 函数作为道具传递给它

export const Tooltip: FC<TooltipProps> = (
  content: Content,
  helperText,
  children,
  ...props
) => 
  const [visible, setVisible] = useState(false);

  const show = () => setVisible(true);
  const hide = () => setVisible(false);

  return (
    <div>
      <Tippy
        content=<Content hide=hide />
        visible=visible
        onClickOutside=hide
        interactive
        ...props
      >
        <div onClick=visible ? hide : show>
        
          // =====>>> **Close button which be in children prop, need to attach hide() function**
          children

        </div>
      </Tippy>
    </div>
  );
;

那么你有:

 <Tooltip
     content= ( hide ) =>
       <div className="popover-buttons">
          
          // Need to attach here **hide()** function from Tooltip coomponent
          <button onClick=hide>
              Cancel
          </button>
          
           <button>
              Delete
           </button>
        </div>
 </Tooltip>

【讨论】:

以上是关于如何在动态子按钮上附加关闭功能?的主要内容,如果未能解决你的问题,请参考以下文章