【问题标题】:How to add a style on a condition in tailwind css如何在顺风CSS中的条件上添加样式
【发布时间】:2021-07-26 17:40:06
【问题描述】:

我正在使用Tailwind CSS在反应中进行侧面,我必须在选择特定链接时添加边界红色。所以我正在使用这种方法但这不起作用任何人都可以在这里帮助我

<li className={"flex items-center space-x-2 px-4 py-5 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-110 border-l-4 border-white" + (window.location.pathname === '/' ? 'border-red-200' : '')}>
              <NavLink to={"/"}>
                <div className="sidebar">
                  <div className="float-left">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-8 w-6 text-red-400"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
                      />
                    </svg>
                  </div>
                  <span className="text-2xl float-right pl-5">
                    Home
                  </span>
                </div>
              </NavLink>
            </li>

【问题讨论】:

标签: javascript css reactjs typescript tailwind-css


【解决方案1】:

使用模板文字,或使用 npm 库classnames

  • 使用模板文字
<... className={`flex items-center space-x-2 px-4 py-5 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-110 border-l-4 border-white ${window.location.pathname === '/' ? 'border-red-200' : ''}`}>

  • 使用类名
import classNames from 'classnames';

<... className={classNames('flex items-center space-x-2 px-4 py-5 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-110 border-l-4 border-white',
    { 
        'border-red-200': window.location.pathname === '/' 
    }
)}>

【讨论】:

    【解决方案2】:
    className={yourItem === value ? 'your-class' : 'or-default-to'}
    

    ` /* 如果您的设置条件为真,则应用类。下面的例子*/

    className={active === value ? 'text-green' : 'text-white'}
    
    class={active === value ? 'text-green' : 'text-white'}
    

    【讨论】:

      【解决方案3】:

      对于 NavLink 组件,您可以使用 activeStyle 属性在链接处于活动状态时应用样式。

      <NavLink
         to="/"
         activeStyle={{
         border-bottom: "2px solid red"; 
            }}
          >
           Link Name
      </NavLink>
      

      【讨论】:

        猜你喜欢
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-03
        • 1970-01-01
        • 1970-01-01
        • 2011-06-23
        • 2013-01-02
        相关资源
        最近更新 更多