【问题标题】:Dynamic Heroicons import with Next.js使用 Next.js 导入动态英雄图标
【发布时间】:2021-10-12 21:38:50
【问题描述】:

我在我的 Next.js 项目中使用 heroicons,由于它目前不支持动态导入(通过将图标名称传递给组件)我创建了自己的组件。

// HeroIcon.tsx
import * as SolidIcons from '@heroicons/react/solid';
import * as OutlineIcons from '@heroicons/react/outline';

interface Props {
  icon: string;
  color?: string;
  size?: number;
  outline?: boolean;
}

export const HeroIcon = (props: Props): JSX.Element => {
  const { icon, color, size, outline = false } = props;

  const { ...icons } = outline ? OutlineIcons : SolidIcons;

  // @ts-ignore
  const Icon: JSX.Element = icons[icon];

  const classes = [
    `${color ? color : 'text-black'}`,
    `h-${size ? size : 6}`,
    `w-${size ? size : 6}`
  ];

  return (
    // @ts-ignore
    <Icon className={classes.join(' ')} />
  );
};

我以后可以这样使用它:

<HeroIcon icon='CogIcon' color='text-blue-600' size={6} outline />

虽然它适用于我的开发服务器:

当我使用npm run build 构建项目并使用npm start 启动它时,我得到了以下结果:

在移动设备上,图标根本不可见。

页面使用 SSG 预渲染,并同时使用 getStaticPathsgetStaticProps

知道可能是什么原因吗?

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

    这段代码有问题

      const classes = [
        `${color ? color : 'text-black'}`,
        `h-${size ? size : 6}`,
        `w-${size ? size : 6}`
      ];
    

    如果您想动态更改 Tailwind CSS 样式,请改为这样编写代码。

      const classes = [
        `${color ? color : 'text-black'}`,
        size ? 'h-12' : 'h-6',
        size ? 'w-12' : 'w-6',
      ];
    

    这是由于 Purge CSS 的工作原理,Tailwind CSS 在后台使用 Purge CSS 来优化您的 Tailwind CSS 类以用于生产。

    遗憾的是,您不能编写像 h-{x} 这样的类,因为 Tailwind CSS 在构建时被清除,而 h-{x} 不会评估为有效的 Tailwind CSS 类。


    参考
    https://v2.tailwindcss.com/docs/optimizing-for-production#writing-purgeable-html

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2019-03-27
      • 1970-01-01
      • 2020-08-31
      • 2021-07-27
      • 2019-10-28
      相关资源
      最近更新 更多