Next.js的类不会更改div元素的属性。

14 浏览
0 Comments

Next.js的类不会更改div元素的属性。

我在nextjs/reactjs中遇到了一个问题。我有两个tsx文件:index.tsx和customAlert.tsx。我的问题是,尽管将css类添加到警报的html元素中,但警报的颜色似乎没有改变。对于css,我使用的是tailwind,它正常工作,不是问题所在。

pages/_app.tsx文件:

import type { AppProps } from "next/app"
import "tailwindcss/tailwind.css"
export default function MyApp({ Component, pageProps }: AppProps) {
    return 
}

components/customAlert.tsx文件:

export default function customAlert(status: string, title: string, message: string) {
    const types: {[key: string]: any} = {success: "green", error: "red", warning: "yellow"}
    const colour = types[status]
    return (
        <>
            {title}
            {message}
        
    )
}

pages/index.tsx文件:

import customAlert from "../components/customAlert"
export default function Index() {
    return (
        {customAlert("success", "hi mom", "hi mom")}
    )
}

应该如何显示的图片:点击此处查看

实际显示的图片:点击此处查看

0
0 Comments

问题的原因是使用动态构建类名的方式导致无法改变div元素的属性。

解决方法是创建一个函数或其他方式来确保使用的所有类名都存在。可以通过以下代码实现:

const getColorClass = (color) => {
  switch (color) {
    case 'success':
      return 'bg-green-100';
    case 'error':
      return 'bg-red-100';
    default:
      return 'bg-yellow-100';
  }
}

这样可以根据颜色参数返回对应的类名,从而实现改变div元素的属性。

0