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

前端 未结 18 853
星月不相逢
星月不相逢 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:20

    I use a pretty hack-ish solution for this in one of my recent applications that works for my purposes, and I find it quicker than writing custom hover settings functions in vanilla js (though, I recognize, maybe not a best practice in most environments..) So, in case you're still interested, here goes.

    I create a parent element just for the sake of holding the inline javascript styles, then a child with a className or id that my css stylesheet will latch onto and write the hover style in my dedicated css file. This works because the more granular child element receives the inline js styles via inheritance, but has its hover styles overridden by the css file.

    So basically, my actual css file exists for the sole purpose of holding hover effects, nothing else. This makes it pretty concise and easy to manage, and allows me to do the heavy-lifting in my in-line React component styles.

    Here's an example:

    const styles = {
      container: {
        height: '3em',
        backgroundColor: 'white',
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'stretch',
        justifyContent: 'flex-start',
        borderBottom: '1px solid gainsboro',
      },
      parent: {
        display: 'flex',
        flex: 1,
        flexDirection: 'row',
        alignItems: 'stretch',
        justifyContent: 'flex-start',
        color: 'darkgrey',
      },
      child: {
        width: '6em',
        textAlign: 'center',
        verticalAlign: 'middle',
        lineHeight: '3em',
      },
    };
    
    var NavBar = (props) => {
      const menuOptions = ['home', 'blog', 'projects', 'about'];
    
      return (
        
    {menuOptions.map((page) =>
    {page}
    )}
    ); }; ReactDOM.render( , document.getElementById('app') );
    .navBarOption:hover {
      color: black;
    }
    
    
    
    

    Notice that the "child" inline style does not have a "color" property set. If it did, this would not work because the inline style would take precedence over my stylesheet.

提交回复
热议问题