【问题标题】:React hover over button cause another button to be hovered over反应悬停在按钮上导致另一个按钮悬停
【发布时间】:2016-04-06 01:27:58
【问题描述】:

对不起标题,我想不出如何简洁地用这个词。

所以我有一组按钮作为 React 组件的一部分:

export default class AdvancedSearch extends React.Component{

    hover(){

    }

    render(){
            return(
                <div className="btn-group">
                    <button id="star1" type="button" className="btn btn-default" onMouseEnter={() => this.hover()}><span className="glyphicon glyphicon-star-empty"></span></button>
                    <button id="star2" type="button" className="btn btn-default" onMouseEnter={() => this.hover()}><span className="glyphicon glyphicon-star-empty"></span></button>
                    <button id="star3" type="button" className="btn btn-default" onMouseEnter={() => this.hover()}><span className="glyphicon glyphicon-star-empty"></span></button>
                    <button id="star4" type="button" className="btn btn-default" onMouseEnter={() => this.hover()}><span className="glyphicon glyphicon-star-empty"></span></button>
                    <button id="star5" type="button" className="btn btn-default" onMouseEnter={() => this.hover()}><span className="glyphicon glyphicon-star-empty"></span></button>
                </div>
            );
    }

我想要发生的是,当我将鼠标悬停在一个按钮上时,它左侧的所有按钮的背景都会发生变化,就好像它们也被悬停在上面一样。我不知道我可以在悬停功能中放置什么来实现这一点,或者这是否是最好的方法。获得这种效果的最佳方法是什么?另外,我希望在单击按钮时也能做同样的事情。

【问题讨论】:

    标签: javascript reactjs hover


    【解决方案1】:

    使用组件状态和 CSS 类。

    export default class AdvancedSearch extends React.Component{
    
    getInitialState() {
        return {
            hoveredIndex: -1
        };
    }
    
    hover(index){
        this.setState({
            hoveredIndex: index
        });
    }
    
    leave() {
        this.setState({
            hoveredIndex: -1
        });
    }
    
    render(){
        var buttons = [];
    
        for (var i = 0; i < 5; i++) {
            let className = 'glyphicon';
            if (i <= this.state.hoveredIndex)
                className += ' glyphicon-star';
            else
                className += ' glyphicon-star-empty';
    
            buttons.push(
                <button id={'star'+(i+1)} type="button" className="btn btn-default" onMouseEnter={this.hover.bind(this, i)} onMouseLeave={this.leave}><span className={className}></span></button>
            );
        }
    
            return(
                <div className="btn-group">
                    {buttons}
                </div>
            );
    }
    

    您应该能够从点击事件或任何其他形式的转换中激发自己;)

    【讨论】:

      猜你喜欢
      • 2019-09-08
      • 2021-08-21
      • 2015-10-18
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多