【问题标题】:messy classnames construction混乱的类名构造
【发布时间】:2017-04-06 19:33:37
【问题描述】:

谁能建议一种方法来清理这个混乱的类名结构:

const ButtonTemplate = props => {
  const themed = `btn-${props.theme}`
  const themedButton = `${styles[themed]} ${themed}${(props.disabled) ? ' disabled' : ''}}`

  return (
    <button className={`${styles.btn} ${themedButton}`} type='button' onClick={props.onClick}>{props.children}</button>
  )
}

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

怎么样

function ButtonTemplate({theme, disabled, onClick, children}) {
  const themed = `btn-${theme}`;
  return (
    <button className={[
      styles.btn,
      styles[themed],
      themed,
      disabled ? 'disabled' : ''
    ].join(" ")} type='button' onClick={onClick}>{children}</button>
  );
}

【讨论】:

    【解决方案2】:

    使用包classnames:

    安装: npm install classnames

    进口: import classNames from 'classnames';

    使用它:)

    const ButtonTemplate = props => {
      const themed = classNames('btn-', props.theme)
      const themedButton = classNames(
        styles.btn,
        styles[themed],
        themed,
        { disabled: props.disabled }
      );
    
      return (
        <button className={themedButton} type='button' onClick={props.onClick}>{props.children}</button>
      )
    }
    

    这很有帮助,因为我们在开发一个大项目的过程中会遇到类似的情况。以下是从original documentation复制的一些技巧:

    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'
    

    ...还有更多。你真的应该看看它并尝试一下。

    【讨论】:

      【解决方案3】:
      const ButtonTemplate = props => {
        const { children, disabled, onClick, theme } = props;
      
        const disabled = disabled ? 'disabled' : '';
        const themed = `btn-${theme}`
        const className = `${styles.btn} ${styles[themed]} ${themed} ${disabled}`;
      
        return (
          <button className={className} type='button' onClick={onClick}>{children}</button>
        )
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-11
        • 2014-01-26
        • 1970-01-01
        • 2014-02-23
        • 2010-11-19
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2013-05-23
        相关资源
        最近更新 更多