【问题标题】:Using dynamic position values in Tailwind CSS在 Tailwind CSS 中使用动态位置值
【发布时间】:2022-06-10 22:10:52
【问题描述】:

我想使用 Tailwind CSS 类将坐标值作为道具传递给组件。每次鼠标悬停时值都会改变,但类不起作用。

我的组件

    import classNames from "classnames";
    interface TooltipProps {
      coordinate: { left: string; top: string; isFavorite: boolean };
    }
    
    const Tooltip: React.FC<TooltipProps> = ({ coordinate }: TooltipProps) => {
      return (
        <div
          id="tooltip"
          className={classNames(
            `fixed ml-[auto] z-[999] p-[10px] text-sm font-medium text-white bg-gray-900 rounded-[6px] shadow-tooltip  dark:bg-gray-700`,
            coordinate.left,
            coordinate.top
          )}
        >
          {coordinate.isFavorite ? "حذف" : "افزودن"} به علاقه‌مندی
          <svg
            className="absolute  bottom-[-10px] center "
            width="16"
            height="10"
            viewBox="0 0 16 10"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path d="M8 10L0 0L16 1.41326e-06L8 10Z" fill="black" />
          </svg>
        </div>
      );
    };
    
    export default Tooltip;

在我传递的道具中:

  setCoordinate({
    top: `top-[${Math.round(top)}px]`,
    left: `left-[${Math.round(left)}px]`,
  });

这些值在使用 Tailwind CSS 实用程序类时不起作用。

【问题讨论】:

    标签: reactjs typescript tailwind-css


    【解决方案1】:

    来自文档:

    Tailwind 不包含任何类型的客户端运行时,因此类名需要在构建时可静态提取,并且不能依赖于在客户端更改的任何类型的任意动态值。在这些情况下使用内联样式,或者将 Tailwind 与 Emotion 等 CSS-in-JS 库结合起来(如果它对您的项目有意义)。

    https://v2.tailwindcss.com/docs/just-in-time-mode

    错误

    <div className={`mt-[${size === 'lg' ? '22px' : '17px' }]`}></div>
    

    正确

    <div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div>
    

    【讨论】:

    • 谢谢。但我保持这种格式
    【解决方案2】:

    您可以${} 在`` 字符串中添加任何变量/动态值。你可以像这样修改className

    className={`fixed ml-[auto] z-[999] p-[10px] text-sm font-medium text-white bg-gray-900 rounded-[6px] shadow-tooltip  dark:bg-gray-700 ${coordinate.left} ${coordinate.right}`}
    

    更多信息你可以参考这个用例和我的回答:here

    【讨论】:

    • 谢谢。但仍然不是火风格
    【解决方案3】:

    Tailwind 不支持动态类,例如您尝试创建的类。完整的实用程序类名称必须在构建时在您的代码中可用,以便 Tailwind 找到它并生成正确的 CSS 类。

    对于像坐标这样动态的东西,我建议使用 style 属性以及保存 Tailwind 实用程序类的 className 属性。

    <div 
      id="tooltip"
      className="fixed ml-auto z-[999] p-[10px] text-sm font-medium text-white bg-gray-900 rounded-[6px] shadow-tooltip dark:bg-gray-700"
      style={{top: `${coordinate.top}px`, left: `${coordinate.left}px`}}
    >
    

    然后您可以将数字位置值传递给您的组件:

    setCoordinate({
      top: Math.round(top),
      left: Math.round(left)
    });
    

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 2010-10-01
      • 2021-04-17
      • 2011-12-03
      • 2020-06-13
      • 2021-07-19
      • 2021-09-02
      • 2021-10-30
      相关资源
      最近更新 更多