凌乱的类名建设

时间:2016-11-22 23:24:11

标签: javascript reactjs ecmascript-6

任何人都可以建议一种方法来清理这个凌乱的classname结构:

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

3 个答案:

答案 0 :(得分:5)

怎么样?
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>
  );
}

答案 1 :(得分:1)

使用包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'

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

答案 2 :(得分:0)

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