简体   繁体   中英

best practice to style react components

I've been working with React for a while and I can't seem to find a good way of styling React components.

One way you could do it is use inline styles but you don't have access to pseudo-elements like :after and :hover which requires you to handle all the "events" with javascript (pretty redundant since you could do this with css).

Another way you could go around this is use style-loader but that would require you to change classes around if you wanna update the UI...(this doesn't feel very "natural" in my opinion).

Or perhaps you could take a hybrid aproach and use style-loader for layout and static styling and then use inline styles for the parts that do need to change. (doesn't feel right either because you have two separate places for your styling).

I am more inclined with using inline styles, this does require some extra javascript and you could work around the :after elements by adding real divs.

What is the best way of doing this?

样式化React的一种好方法是使用样式化的组件

The best way is to use Radium for pseudo elements or media queries

class Button extends React.Component {
  render() {
    return (
      <button
        style={{styles}}>
        {this.props.children}
      </button>
    );
  }
}

Button = Radium(Button);


const styles = {
    backgroundColor: red,
    ':hover': {
        backgroundColor: black
    }
};

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