React onMouseEnter / onMouseLeave没有按预期工作(奇怪的行为)

时间:2018-03-12 05:11:47

标签: javascript reactjs

我正在尝试为我的网格项创建指标,因此它会将红色标记作为背景颜色。但是修改DOM似乎反应很慢,并且某些组件没有更新

这是我的代码, 我循环项目

{(function(rows, i, len) {
    while (++i <= len) {
    rows.push (<div
        key={i.toString()}
        className={"col-sm-3 bg-light mb-1 p-3 parent"}
        style={that.styles.item}
        onMouseEnter={that.itemMouseEnter}
        onMouseLeave={that.itemMouseLeave}>
        <center>
            <button type="button" class="close" aria-label="Close" style={that.styles.closeButton}>
                <span aria-hidden="true">&times;</span>
            </button>
            <div className="rounded-circle img-responsive mb-3" style={that.styles.image} />
            <h4>VicoErv</h4>
        </center>
    </div>)
    }

    return rows;
})([], 0, 10)}

项目监听器

itemMouseEnter(event) {
    event.stopPropagation();
    let elem = event.target;

    elem.classList.remove('bg-light');
    elem.classList.add('bg-danger');
}

itemMouseLeave(event) {
    event.stopPropagation();
    let elem = event.target;

    elem.classList.remove('bg-danger');
    elem.classList.add('bg-light');
}

这里我附上gif

react strange

是否有任何解决方案可以做出反应?

1 个答案:

答案 0 :(得分:1)

使用反应bindstate

解决
{(function(rows, i, len) {
    while (++i <= len) {
    rows.push (<div
        key={i.toString()}
        className={"col-sm-3 " + (that.state.itemSelected === i ? 'bg-danger' : 'bg-light') + " mb-1 p-3 parent"}
        style={that.styles.item}
        onMouseEnter={that.itemMouseEnter.bind(that, i)}
        onMouseLeave={that.itemMouseLeave.bind(that, i)}>
        <center>
            <button type="button" className="close" aria-label="Close" style={that.styles.closeButton}>
                <span aria-hidden="true">&times;</span>
            </button>
            <div className="rounded-circle img-responsive mb-3" style={that.styles.image} />
            <h4>VicoErv</h4>
        </center>
    </div>)
    }

    return rows;
})([], 0, 10)}

事件功能

itemMouseEnter(id, e) {
    e.preventDefault();
    e.stopPropagation();
    let elem = e.target;

    this.setState({itemSelected: id})
}

itemMouseLeave(id, e) {
    e.preventDefault();
    let elem = e.target;

    this.setState({itemSelected: false});
}