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

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

    I'm not 100% sure if this is the answer, but its the trick i use to simulate the CSS :hover effect with colours and images inline.

    `This works best with an image`
    
    class TestHover extends React.PureComponent {
    render() {
    const landingImage = {     
    "backgroundImage": "url(https://i.dailymail.co.uk/i/pix/2015/09/01/18/2BE1E88B00000578-3218613-image-m-5_1441127035222.jpg)",
    "BackgroundColor": "Red", `this can be any color`
    "minHeight": "100%",
    "backgroundAttachment": "fixed",
    "backgroundPosition": "center",
    "backgroundRepeat": "no-repeat",
    "backgroundSize": "cover", 
    "opacity": "0.8", `the hove trick is here in the opcaity slightly see through gives the effect when the background color changes`
        }
    
      return (
        
          ); 
      }
    }
    ReactDOM.render(
        ,
      document.getElementById("root")
    );
    

    CSS:

    .menu {
    top: 2.70em;
    bottom: 0px;
    width: 100%;
    position: absolute;
    }
    
    .menu-item {
    cursor: pointer;
    height: 100%;
    font-size: 2em;
    line-height: 1.3em;
    color: #000;
    font-family: "Poppins";
    font-style: italic;
    font-weight: 800;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
    }
    

    Before hover

    .menu-item:nth-child(1) {
    color: white;
    background-color: #001b37;
    } 
    

    On hover

    .menu-item:nth-child(1):hover {
    color: green;
    background-color: white;
    }
    

    Example: https://codepen.io/roryfn/pen/dxyYqj?editors=0011

提交回复
热议问题