我非常喜欢React中的内联CSS模式,并决定使用它。

但是,你不能使用:hover和类似的选择器。那么,在使用内联CSS样式时实现高亮悬停的最佳方法是什么呢?

#reactjs的一个建议是有一个Clickable组件,并像这样使用它:

<Clickable>
    <Link />
</Clickable>

Clickable有一个悬停状态,并将其作为道具传递给链接。然而,Clickable(我实现它的方式)将链接包装在一个div中,以便它可以设置onMouseEnter和onMouseLeave。这让事情变得有点复杂(例如,在div中包装的span与span的行为不同)。

有没有更简单的方法?


当前回答

我找到了一种干净的方法,用useState的包装器来做到这一点,我称之为useHover。 不需要额外的库/框架。

const App = () => {

    const hover = useHover({backgroundColor: "LightBlue"})

    return <p {...hover}>Hover me!</p>
}

包装器的代码:

function useHover(styleOnHover: CSSProperties, styleOnNotHover: CSSProperties = {})
{
    const [style, setStyle] = React.useState(styleOnNotHover);

    const onMouseEnter = () => setStyle(styleOnHover)
    const onMouseLeave = () => setStyle(styleOnNotHover)

    return {style, onMouseEnter, onMouseLeave}
}

注意,当组件未悬停时,useHover有一个可选的第二个参数用于样式。

在这里试试吧

其他回答

补充乔纳森的回答,这里是事件覆盖的焦点和活跃状态,使用onMouseOver而不是onMouseEnter,因为后者不会冒泡,如果你有任何子元素的目标事件被应用到。

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(
      <div>
        <a style={linkStyle} 
          onMouseOver={this.toggleHover} 
          onMouseOut={this.toggleHover} 
          onMouseUp={this.toggleActive} 
          onMouseDown={this.toggleActive} 
          onFocus={this.toggleFocus}> 
          Link 
        </a>
      </div>
    )
  }

最简单的方式:2022年: useRef +内联onMouseOver/onMouseOut

例子:

 var bottomAtag = useRef(null)
    
   

...然后在里面返回(

 <a ref={bottomAtag} onMouseOver={() => bottomAtag.current.style.color='#0F0'} ...></a>

你可以使用镭——它是一个开源工具,可以在ReactJS中使用内联样式。它恰好添加了您需要的选择器。非常受欢迎,看看npm上的镭

我做了类似的事情,但我没有使用material-ui或makestyle。我在样式对象的css中添加了悬停作为条件:

const styles = {
  hoverStyle: {
    color: 'grey',
    '&:hover': { color: 'blue !important' },
  }
};

var NavBar = (props) => {
  const menuOptions = ['home', 'blog', 'projects', 'about'];

  return (
    <div>
      <div>
        {menuOptions.map((page) => <div style={styles.hoverStyle} key={page}>{page}</div> )}
      </div>
    </div>
  );
};

这对我很管用。

直接在组件中使用标签,如下所示:

<Wrapper>
  <style>
   .custom-class{
       // CSS here
   }
   .custom-class:hover{
     //query selector
   }
  </style>
  <div className="custom-class"></div>
</Wrapper>