凌乱的类名构造

IT技术 javascript reactjs ecmascript-6
2021-05-04 14:48:29

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

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个回答

关于什么

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

使用包类名

安装: 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>
  )
}

这可能非常有帮助,因为我们将在开发一个大项目的过程中面临类似的情况。以下是从原始文档中复制的一些技巧

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'

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

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