Inline CSS styles in React: how to implement a:hover?

前端 未结 18 908
星月不相逢
星月不相逢 2020-11-28 21:51

I quite like the inline CSS pattern in React and decided to use it.

However, you can\'t use the :hover and similar selectors. So what\'s the best way to

18条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 22:25

    I'm in the same situation. Really like the pattern of keeping the styling in the components but the hover states seems like the last hurdle.

    What I did was writing a mixin that you can add to your component that needs hover states. This mixin will add a new hovered property to the state of your component. It will be set to true if the user hovers over the main DOM node of the component and sets it back to false if the users leaves the element.

    Now in your component render function you can do something like:

    
    

    Now each time the state of the hovered state changes the component will rerender.

    I've also create a sandbox repo for this that I use to test some of these patterns myself. Check it out if you want to see an example of my implementation.

    https://github.com/Sitebase/cssinjs/tree/feature-interaction-mixin

提交回复
热议问题