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

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

    
      
        Go
      
    
    

    Where Hoverable is defined as:

    function Hoverable(props) {
      const [hover, setHover] = useState(false);
    
      const child = Children.only(props.children);
    
      const onHoverChange = useCallback(
        e => {
          const name = e.type === "mouseenter" ? "onMouseEnter" : "onMouseLeave";
          setHover(!hover);
          if (child.props[name]) {
            child.props[name](e);
          }
        },
        [setHover, hover, child]
      );
    
      return React.cloneElement(child, {
        onMouseEnter: onHoverChange,
        onMouseLeave: onHoverChange,
        style: Object.assign({}, child.props.style, hover ? props.hoverStyle : {})
      });
    }
    

提交回复
热议问题