How to add multiple classes to a ReactJS Component?

后端 未结 29 2085
执念已碎
执念已碎 2020-11-27 09:16

I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on eac

相关标签:
29条回答
  • 2020-11-27 09:47

    I usually use it like this : (in your case)

        <li  key={index} className={
            "component " +
            `${activeClass? activeClass: " not-an-active-class "}` +
            `${data.class? " " + data.class : " no-data-class "}`
       } />
    

    When it comes to JSX and (usually) we have some json... than you loop it ... component.map, plus some conditional to check if json property exists to render class name depending on property value from JSON. In example below component_color and component_dark_shade are properties from component.map()

       <div className={
            "component " +
            `${component_color? component_color: " no-color "}` +
            `${component_dark_shade? " " + component_dark_shade : " light "}`
       }/>
    

    Output : <div class="component no-color light" .... Or: <div class="component blue dark" .... depending on values from map...

    0 讨论(0)
  • 2020-11-27 09:48

    That's what I do:

    Component:

    const Button = ({ className }) => (
      <div className={ className }> </div>
    );
    

    Calling Component:

    <Button className = 'hashButton free anotherClass' />
    
    0 讨论(0)
  • 2020-11-27 09:49

    I am using React 16.6.3 and @Material UI 3.5.1, and is able to use arrays in className like className={[classes.tableCell, classes.capitalize]}

    So in your example, the following would be similar.

    <li key={index} className={[activeClass, data.class, "main-class"]}></li>
    
    0 讨论(0)
  • 2020-11-27 09:50

    for more classes adding

    ... className={`${classes.hello} ${classes.hello1}`...
    
    0 讨论(0)
  • 2020-11-27 09:50

    You can use arrays and then join them using space.

    <li key={index} className={[activeClass, data.class, "main-class"].join(' ')}></li>
    

    This will result in :

    <li key={index} class="activeClass data.class main-class"></li>
    
    0 讨论(0)
提交回复
热议问题