gpt4 book ai didi

javascript - ReactJS:onMouseEnter 只有在被点击时才会触发

转载 作者:行者123 更新时间:2023-11-29 21:10:44 27 4
gpt4 key购买 nike

我运行下面的代码:我返回一个 div 数组,我希望它们在鼠标输入(悬停)时更改背景。只有当我点击它时事件才会触发。这是因为我需要选择 div 吗?我已经尝试过 tab index = 0 和 tab index = 1!非常感谢您的帮助!!!

class OneView extends React.Component {
constructor(props) {
super(props);
this.handleEnter = this.handleEnter.bind(this);
this.handleExit = this.handleExit.bind(this);
this.state = {
hover: false
}
}
handleEnter(e) {
this.setState({hover: true});
}
handleExit(e) {
this.setState({hover: false});
}
render() {
var specificStyle = {
textAlign: 'center',
flex: 1,
backgroundColor : this.state.hover ? '#111' : '#CCC',
};
return(
<div style={Object.assign(genericStyle, specificStyle)} onMouseEnter={this.handleEnter} onMouseOut={this.handleExit}>
Test
</div>
);
}
}

function GenerateMatrix() {
var firstMatrix = [];
var specificStyle = {
display:"inline-flex",
flexDirection:'row',
flex: 1
};
for (var i = 1; i < 8; i++) {
firstMatrix.push(<OneView/>);
}
return (
<div style={Object.assign(genericStyle, specificStyle)}>
{firstMatrix}
</div>
);
}

最佳答案

摆脱 genericStyle 并使用 specificStyle 才有效

class OneView extends React.Component {
constructor(props) {
super(props);
this.handleEnter = this.handleEnter.bind(this);
this.handleExit = this.handleExit.bind(this);
this.state = {
hover: false
}
}
handleEnter(e) {
this.setState({hover: true});
}
handleExit(e) {
this.setState({hover: false});
}
render() {
var specificStyle = {
textAlign: 'center',
flex: 1,
backgroundColor : this.state.hover ? '#111' : '#CCC',
};
return(
<div style={Object.assign(specificStyle)} onMouseEnter={this.handleEnter} onMouseOut={this.handleExit}>
Test
</div>
);
}
}

function GenerateMatrix() {
var firstMatrix = [];
var specificStyle = {
display:"inline-flex",
flexDirection:'row',
flex: 1
};
for (var i = 1; i < 8; i++) {
firstMatrix.push(<OneView/>);
}
return (
<div style={Object.assign(specificStyle)}>
{firstMatrix}
</div>
);
}

ReactDOM.render(<GenerateMatrix/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

关于javascript - ReactJS:onMouseEnter 只有在被点击时才会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42016657/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com