这是我的反应组件
const ButtonComponent = ({ children, onClick, disabled, className = "" }) => {
console.log("class name is ", className);
const buttonClassName = `
bg-green-700
flex
hover:bg-green-500
transition
duration-300
ease-in-out
text-white
h-auto
text-base
p-2
rounded-[5px]
m-2
${
disabled
? "bg-teal-200 text-teal-800 cursor-not-allowed"
: "cursor-pointer"
}
${className}
`;
return (
<button onClick={onClick} className={buttonClassName} disabled={disabled}>
{children}
</button>
);
};
导出默认ButtonComponent;
console.log 工作正常,但在 JSX 中,className 属性没有给出正确的值。
我认为问题出在 tailwind css 上,如果您不在 className 属性中直接使用类,则 tailwind 不会构建类。如果您确定在项目中使用类,请在 tailwind 配置文件中使用 safelist 指令,或在条件语句中使用类的全名。
这篇文章讨论了这个问题 https://www.vincentschmalbach.com/tailwind-css-and-dynamic-or-conditional-class-names-in-vue/
适用于 vue,但解释一下问题。
如果 className 设置正确,但样式未按预期显示,请确保不存在 CSS 特异性或冲突问题。例如,由于更高的特异性或较晚的源顺序,样式表中的其他样式可能会覆盖您通过 className prop 设置的样式。
试试这个。
import React from 'react';
const ButtonComponent = ({ children, onClick, disabled, className = "" }) => {
// Ensuring no leading/trailing spaces in the provided className
const trimmedClassName = className.trim();
// Construct the complete class name with conditionals and the provided className
const buttonClassName = `
bg-green-700
flex
hover:bg-green-500
transition
duration-300
ease-in-out
text-white
h-auto
text-base
p-2
rounded-[5px]
m-2
${disabled ? "bg-teal-200 text-teal-800 cursor-not-allowed" : "cursor-pointer"}
${trimmedClassName} // Add the user-provided classes
`.trim(); // Trim any accidental leading/trailing whitespace in the entire class string
// Log the final class names for debugging purposes
console.log("Final class name:", buttonClassName);
return (
<button onClick={onClick} className={buttonClassName} disabled={disabled}>
{children}
</button>
);
};
export default ButtonComponent;
我希望能帮到你。