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

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

    I think onMouseEnter and onMouseLeave are the ways to go, but I don't see the need for an additional wrapper component. Here is how I implemented it:

    var Link = React.createClass({
      getInitialState: function(){
        return {hover: false}
      },
      toggleHover: function(){
        this.setState({hover: !this.state.hover})
      },
      render: function() {
        var linkStyle;
        if (this.state.hover) {
          linkStyle = {backgroundColor: 'red'}
        } else {
          linkStyle = {backgroundColor: 'blue'}
        }
        return(
          
        )
    }
    

    You can then use the state of hover (true/false) to change the style of the link.

提交回复
热议问题