如何在React中向DOM元素添加动态的TailwindCSS类

4

我是TailWindCSS的新手,我想在一个按钮元素中添加启用/禁用样式。如何有条件地添加禁用特定的样式/类(例如,假设我需要添加"opacity-50 cursor-not-allowed")到按钮上?

    <button
          className="bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4 border-b-4 border-blue-700 hover:border-blue-500 rounded mr-3"
          disabled={!globalContext.users.length > 0}
          onClick={handleClearResultsClick}
        >
          Clear Results
    </button>

2
这个回答解决了你的问题吗?React Js有条件地应用类属性 - Remul
是的,它做到了。谢谢。 - user10828808
2个回答

8
  • You can use the new ES6 "template strings".

  • This is a simple React component that has disabled the (-) button when counter <= 0

  • .pointer-even-none is the tailwindCSS class that renders the disable button

    const [count, setCount] = useState(0);
    
    return (
      <Fragment>
           {/* button Substract with styles tailwind*/}
          <button className={`p-2 ${count <= 0 ? 'opacity-50 pointer-events-none': 'bg-red-700'}`} 
                  onClick={() => setCount( count - 1 )}>
                  Substract
          </button>
    
          {/* Counter */}
          <span className="p-2">{ count }</span>
    
          {/* button Add whit styles tailwind*/}
          <button className="p-2 bg-green-700"
                  onClick={() => setCount(count + 1 )}>
                  Add
          </button>
      </Fragment>
    )
    

如果在项目中没有使用opacity-50类,则它不会出现在编译后的代码中。根据我的测试,它不会出现在编译后的CSS中,也无法正常工作。如果有解决方法,请告诉我。如果您的动态类别在其他地方使用,则应该没问题。 - m-farhan

1
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

你可以使用这个轻量级库的类名:https://www.npmjs.com/package/classnames。它将使事情变得整洁。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接