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

如何调整Chakra UI Popover内容布局,使按钮位于文本右侧

解决Chakra UI SelectableTooltip组件布局问题

要实现按钮在文本右侧且内容不溢出的布局,可以通过调整PopoverContent和PopoverBody的flex属性来解决,具体修改后的代码如下:

import {
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverBody,
  Portal,
  Button,
} from "@chakra-ui/react";
import { ReactNode } from "react";
import { CopyIcon } from "@chakra-ui/icons";

export function SelectableTooltip({
  textComponent,
  label,
}: {
  textComponent: ReactNode;
  label: string;
}) {
  return (
    <Popover trigger="hover" openDelay={100}>
      <PopoverTrigger>{textComponent}</PopoverTrigger>
      <Portal>
        <PopoverContent display="flex" alignItems="center" gap="2" p="3">
          <PopoverBody flex={1} whiteSpace="normal" p={0}>
            {label}
          </PopoverBody>
          <Button
            rightIcon={<CopyIcon />}
            size="sm"
            variant="ghost"
            onClick={() => navigator.clipboard.writeText(label)}
          >
            复制
          </Button>
        </PopoverContent>
      </Portal>
    </Popover>
  );
}

关键调整说明:

  • PopoverContent:设置display="flex"实现横向布局,alignItems="center"让文本与按钮垂直居中对齐;gap="2"为元素间添加合理间距;p="3"统一容器内边距,优化视觉效果。
  • PopoverBody:添加flex={1}使其占据容器剩余宽度,避免按钮挤压文本区域;whiteSpace="normal"允许文本自动换行,彻底解决内容溢出问题;p={0}移除默认内边距,避免布局错位。
  • Button:新增variant="ghost"让按钮风格更贴合tooltip的轻量定位,同时添加“复制”文本提升交互可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:37:21