You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将trigger props传递给仅为按钮或文本的children对象

实现方案

你可以直接用React内置的React.cloneElementAPI完成props注入,你拿到的children是已经生成的React元素实例,不能直接作为组件标签使用,克隆元素的时候可以传入需要追加的triggerProps,自动和元素原有props合并。

核心代码修改

export const PopOver = ({
  children,
  headerText,
  bodyText,
  hasHeader,
  hasBody,
  hasFooter,
  cancelButtonText,
  okButtonText,
  hasCloseButton,
  onOkPress,
  onCancelPress,
  ...rest
}: PopoverProps): JSX.Element => {
  return (
    <Popover
      trigger={(triggerProps) => {
        // 兼容文本/数字类型的children,自动包一层Button
        if (['string', 'number'].includes(typeof children)) {
          return <Button {...triggerProps}>{children}</Button>
        }
        // 给元素类型的children注入triggerProps
        return React.cloneElement(children, triggerProps)
      }}
      {...rest}
    >
    {/* 其余Popover内容逻辑保持不变 */}
    </Popover>
  )
}

说明

  • 追加的triggerProps如果和children原有props重名,会自动覆盖原有props,符合触发弹窗的交互逻辑要求
  • 如果你可以确保传入的children永远是React元素(不存在纯文本/数字的情况),可以去掉类型判断的兼容逻辑,直接返回克隆后的元素即可。

内容的提问来源于stack exchange,提问作者Ackman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:21:03