首页  >  问答  >  正文

在Next.js中应用TailwindCSS样式时,遇到样式未渲染的问题

<p>使用TailwindCSS设置背景封面,我在useEffect中从bookId(10位数字)中提取了颜色。颜色得到更新,并且组件使用更新后的颜色值重新渲染,但渲染页面的背景颜色仍然是其父div的相同颜色。</p> <pre class="brush:php;toolbar:false;">const colors = [ 'from-red-500', 'from-orange-500', 'from-yellow-500', 'from-green-500', 'from-cyan-500', 'from-blue-500', 'from-indigo-500', 'from-violet-500', 'from-purple-500', 'from-pink-500', ] function BgCover(props) { const [color, setColor] = useState(null) const router = useRouter() useEffect(() => { const id = router.query.bookId const index = id.slice(-1) //从bookId中提取索引 const bgColor = colors[index] setColor(bgColor) }, []) return ( <Fragment> {color ? ( <div className='flex-grow scrollbar-hide select-none relative'> <div className={`bg-gradient-to-b ${color} to-black`}> <section className={`flex flex-col md:flex-row items-center justify-center p-4`}> {props.children} </section> </div> </div> ) : ( <p className='text-2xl'>加载中..</p> )} </Fragment> ) }</pre> <p>但是,当我用颜色值(比如'from-red-500')替换color变量时,渲染页面中的背景颜色是可见的。</p> <p>我还尝试用getStaticProps替换useEffect中的setColor代码,但静态版本的代码无法解决这个问题(当使用color变量时)。</p> <p>感谢任何帮助。</p>
P粉933003350P粉933003350390 天前556

全部回复(1)我来回复

  • P粉191323236

    P粉1913232362023-08-28 00:23:31

    这是tailwindcss和动态类的已知问题,因为类是在渲染后应用的,所以它的效果不会被tailwind生成,除非有另一个元素具有与静态类相同的类。

    因此,您可以使用tailwind的"safelist"来解决这个问题。 在您的tailwind.config中,定义一个safelist数组,包含您需要生成的所有tailwind类,而这些类在您的代码中不存在作为静态类。

    tailwind.config.js:

    module.exports = {
      content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
      ],
      safelist: [
        'from-red-500',
        'from-orange-500',
        'from-yellow-500',
        'from-green-500',
        'from-cyan-500',
        'from-blue-500',
        'from-indigo-500',
        'from-violet-500',
        'from-purple-500',
        'from-pink-500',
      ]
      // ...
    }

    现在这些类将始终被生成,因此当您动态应用它们时,它们将相应地更改。

    请注意,在添加到safelist后,您需要重新启动服务器。

    来源

    另一个手动解决方案是创建一个隐藏元素,并将所有所需的类添加到它中,这样即使在渲染后动态获取它们,它们也会被生成。

    <div className="hidden from-red-500"></div>

    但我认为safelist更好。

    回复
    0
  • 取消回复