为什么React通过onMouseOver和onMouseOut修改样式会不生效?

新手上路,请多包涵

问题描述

这是一个React组件,设计师要求的是当鼠标移动到这个Item上时在Item的右侧展示圆角效果,同时背景色变为灰色,而在选中的时候背景色变为蓝色。现在的问题是,单就鼠标移动到Item上这个效果,下面的代码貌似没办法正常工作,鼠标移入的时候确实会展示背景色,但紧接着移出去的时候背景色并不会消失。

问题出现的环境背景及自己尝试过哪些方法

我尝试通过console.log来打印bgColor的值以监控它的变化,但是我发现bgColor的值修改动作是正常的,仅仅是没有应用到样式上面而已。

相关代码

class BasicItem extends Component {
    constructor(props) {
        super(props);

        this.state = {
            IsHover: false,
            IsSelect: false,
        }
    }

    render() {
        let bgColor = 'none';
        if (this.state.IsHover) {
            bgColor = '#E6E7E9'
        } else if (this.state.IsSelect) {
            bgColor = 'rgba(66,133,244,.1)'
        } else {
            bgColor = 'none'
        }
        console.log(bgColor);

        return (
            <div style={{
                height: '48px', width: '100%',
                borderRadius: (this.state.IsSelect || this.state.IsHover) ? '0 25px 25px 0' : 'none',
                backgroundColor: bgColor,
                color: '#1967D2',
                font: '500 14px/20px "Helvetica Neue", sans-serif',
            }}
                onMouseOver={() => this.setState({ IsHover: true })}
                onMouseOut={() => this.setState({ IsHover: false })}>{this.props.children}</div>
        )
    }
}
阅读 4.5k
2 个回答

不知道 是不是这样的效果
demo

新手上路,请多包涵

发现问题了,background-color的取值没有none这个说法,如果要设置透明背景要用transparent才可以

推荐问题