代码之家  ›  专栏  ›  技术社区  ›  Obscenity

同构样式加载器-如何添加“活动”类

  •  1
  • Obscenity  · 技术社区  · 8 年前

    我正在使用 react-starter-kit 并构建如下所示的列表组件:

    import React from 'react';
    import withStyles from 'isomorphic-style-loader/lib/withStyles';
    import s from './CommandList.css';
    
    const CommandList = () => {
      return (
        <ul className={s.commandList}>
          {data.commands.map((command, index) => (
            <li 
              key={index}
              className={s.commandListItem}>
              {command.command}
            </li>
          ))} 
        </ul>
      );
    };
    
    export default withStyles(s)(CommandList);
    

    我正在尝试向我的 li 项目,但不确定如何进行?我试着用 classnames 但不确定如何从我的风格中获得第二类。当我只是传入字符串“active”时,样式不会被导入。

    import cx from 'classnames';
    
    <li className={cx(s.commandListItem, {'active': command.active })}>
    

    我的问题是,我将如何做以下事情:

    <li className={cx(s.commandListItem, {s.active: command.active })}>
    
    3 回复  |  直到 8 年前
        1
  •  1
  •   Obscenity    8 年前

    找到了答案。我在使用 classnames 错误的我需要导入 classnames/bind 。

    import s from './CommandList.css';
    import classnames from 'classnames/bind';
    
    let cx = classnames.bind(s);
    

    然后,我可以像我想要的那样传入“active”字符串:

    <li className={cx(s.commandListItem, {'active': command.active })}>
    

    这个 cx var名称现在更有意义了

        2
  •  0
  •   SherylHohman David    8 年前

    <li className={cx(s.commandListItem, {[s.active]: command.active })}>
    看见 [] 对象键表示法

        3
  •  0
  •   Mohammad    8 年前

    类名 在React中是String,您必须将所有对象转换为String

    首先创建一个要分配给类的类数组

    然后将类名的数组转换为字符串

    className={[s.commandListItem, 'active'].join('')}