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

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

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

<Clickable>
    <Link />
</Clickable>

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

有没有更简单的方法?


当前回答

onMouseOver和onMouseLeave with setState起初似乎对我来说有点开销-但这就是react的工作方式,对我来说这似乎是最简单和最干净的解决方案。

例如,呈现一个主题CSS服务器端也是一个很好的解决方案,可以使react组件更干净。

如果你不需要将动态样式附加到元素(例如主题),你就不应该使用内联样式,而应该使用CSS类。

这是一个传统的html/css规则,以保持html/ JSX干净简单。

其他回答

我认为onMouseEnter和onMouseLeave是可行的方法,但我不认为需要额外的包装器组件。以下是我如何实现它:

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(
      <div>
        <a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
      </div>
    )
}

然后,您可以使用悬停状态(true/false)来更改链接的样式。

您可以使用css模块作为替代方案,另外还可以使用react-css-modules进行类名映射。

这样你就可以像下面这样导入你的样式,并在你的组件中使用正常的css范围:

import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';

class Table extends React.Component {
    render () {
        return <div styleName='table'>
            <div styleName='row'>
                <div styleName='cell'>A0</div>
                <div styleName='cell'>B0</div>
            </div>
        </div>;
    }
}

export default CSSModules(Table, styles);

下面是一个webpack css模块的例子

onMouseEnter={(e) => {
    e.target.style.backgroundColor = '#e13570';
    e.target.style.border = '2px solid rgb(31, 0, 69)';
    e.target.style.boxShadow = '-2px 0px 7px 2px #e13570';
}}
onMouseLeave={(e) => {
    e.target.style.backgroundColor = 'rgb(31, 0, 69)';
    e.target.style.border = '2px solid #593676';
    e.target.style.boxShadow = '-2px 0px 7px 2px #e13570';
}}

在样式或类中设置默认属性,然后调用onMouseLeave()和onMouseEnter()来创建悬停功能。

签出类型样式,如果你使用React和Typescript。

下面是:hover的示例代码

import {style} from "typestyle";

/** convert a style object to a CSS class name */
const niceColors = style({
  transition: 'color .2s',
  color: 'blue',
  $nest: {
    '&:hover': {
      color: 'red'
    }
  }
});

<h1 className={niceColors}>Hello world</h1>

对于styles -components和react-router v4,你可以这样做:

import {NavLink} from 'react-router-dom'

const Link = styled(NavLink)`     
  background: blue;

  &:hover {
    color: white;
  }
`

...
<Clickable><Link to="/somewhere">somewhere</Link></Clickable>