【问题标题】:Adding a className dynamically in React.js with Tailwind.css使用 Tailwind.css 在 React.js 中动态添加类名
【发布时间】:2022-01-23 18:19:06
【问题描述】:

假设我有一个 React 组件,它从 props 获取 Tailwind 类名 例如:

import React from "react";

export default function Header({navColor}) {

  return (
    <nav
    className="flex justify-center items-center text-white  text-xl h-14"> //I want to add a class that it's name is the (navColor) value to the nav tag 
      TEST
    </nav>
  );
}

如何做到这一点?

【问题讨论】:

  • 这个 npm 包更适合这个目的 => npmjs.com/package/classnames
  • 谢谢,使用这个库相对于模板文字有什么好处?
  • 它抽象出了所有可能的方法,可以在不同的条件下动态设置类名到一个函数中。您可以在任何地方重复使用它。

标签: reactjs react-hooks tailwind-css


【解决方案1】:

您可以使用Template literals 来实现这一目标

反引号 ``

中使用${}
<nav
    className={`flex justify-center items-center text-white  text-xl h-14 ${navColor}`}> 
      TEST
</nav>

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 2021-04-09
    • 2015-04-14
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多