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

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

    Adding on to Jonathan's answer, here are the events to cover the focus and active states, and a using onMouseOver instead of onMouseEnter since the latter will not bubble if you have any child elements within the target the event is being applied to.

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

提交回复
热议问题