【问题标题】:How to add dynamic TailwindCSS classes to DOM elements in React如何将动态 TailwindCSS 类添加到 React 中的 DOM 元素
【发布时间】:2020-08-05 22:44:48
【问题描述】:

我是 TailWindCSS 的新手,我想为 Button 元素添加启用/禁用样式。如何有条件地向按钮添加禁用的特定样式/类(即假设我需要添加“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>

【问题讨论】:

标签: css reactjs tailwind-css


【解决方案1】:
  • 您可以使用新的ES6 "template strings"

  • 这是一个简单的React component,它在计数器 时禁用了 (-) 按钮

  • .pointer-even-none 是呈现禁用按钮的 tailwindCSS 类

    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>
    )
    

【讨论】:

    【解决方案2】:

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

    // 大量不同类型的参数 classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

    // 其他假值被忽略 classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

    你可以使用这个轻量级库类名

    https://www.npmjs.com/package/classnames

    它会让事情变得整洁

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 2017-11-08
      • 2016-06-02
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2012-05-31
      相关资源
      最近更新 更多