简体   繁体   中英

How to create and apply dynamic stylesheet based CSS class in ReactJS?

Is there any standard way to add dynamic stylesheet based CSS class into DOM using ReactJS (I am not talking about inline styles) ?

I know I could do this using standard JavaScript or jQuery, probably best in componentDidMount life cycle event, but I am curious if there's any standard way of doing this purely using React, that also reduces DOM mutation as much as possible.

Also please note that I am talking in the context of a simple web application that does not use nodejs.

The recommended way is to use classnames . it is a function that takes an object of keys that are either true or false, and returns a string of only true keys.

so you would do something like:

...
import cx from 'classnames';

const MyComponent = React.createClass({
   propTypes: {
      isVisible: React.PropTypes.bool
   },

   render() {
      let classes = cx({
                css-class: true,
                css-visible: !!this.props.isVisible   
             });

      return (
              <div className={classes}>
                 Hello World!
              </div>
      )
   }
});

this would create a div that gets the css classes css-class and css-visible , however css-visible would only be applied if this.props.isVisible existed or was true.

UPDATE: to include the css properties themselves.

...
render() {
   let styles = { "border": "1px solid black" };

   return (
      <div style={styles}>
        Hello World!
      </div>
   );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM