Pau*_*bro 5 typescript reactjs next.js
我在 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(' ')} />
);
};
Run Code Online (Sandbox Code Playgroud)
我稍后可以这样使用它:
<HeroIcon icon='CogIcon' color='text-blue-600' size={6} outline />
Run Code Online (Sandbox Code Playgroud)
当我构建项目并npm run build启动它时,npm start我得到了这个结果:

在移动设备上,图标根本不可见。
该页面是使用 SSG 预渲染的,并使用getStaticPaths和getStaticProps。
知道可能是什么原因吗?
小智 2
这段代码有问题
const classes = [
`${color ? color : 'text-black'}`,
`h-${size ? size : 6}`,
`w-${size ? size : 6}`
];
Run Code Online (Sandbox Code Playgroud)
如果您想动态更改 Tailwind CSS 样式,请像这样编写代码。
const classes = [
`${color ? color : 'text-black'}`,
size ? 'h-12' : 'h-6',
size ? 'w-12' : 'w-6',
];
Run Code Online (Sandbox Code Playgroud)
这是由于 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
| 归档时间: |
|
| 查看次数: |
6596 次 |
| 最近记录: |