[英]Element focus when hover
我想创建一个按钮,其样式在悬停时会更改,并一直保持这种状态,直到发生另一次悬停为止。 从本质上讲,我想创建一个按钮,其重点是通过悬停改变,因为看到这里 。 我想我可以通过一些函数更改父子之间的状态来做到这一点,但是有没有更简单的方法呢? 谢谢。
class Button extends React.Component { render() { return ( <button>{this.props.title}</button> ); } } class Parent extends React.Component { render() { return ( <div> <Button title={"button 1"}/> <Button title={"button 2"}/> <Button title={"button 3"}/> </div> ); } } ReactDOM.render(<Parent />, app);
button:hover { background-color: yellow; }
<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> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"></div>
Parent
是唯一知道按钮的地方,并且由于active
更改需要持续进行,因此您需要更改状态:
class Button extends React.Component { onHover = () => this.props.onHover(this.props.buttonId); render() { const { title, activeId, buttonId } = this.props; return ( <button onMouseOver={this.onHover} className={ activeId === buttonId ? 'active' : '' }> {title} </button> ); } } class Parent extends React.Component { constructor(props) { super(props); this.state = { activeId: null } } onButtonHover = (activeId) => this.setState({ activeId }); render() { const { activeId } = this.state; return ( <div> <Button title={"button 1"} onHover={this.onButtonHover} buttonId={0} activeId={ activeId } /> <Button title={"button 2"} onHover={this.onButtonHover} buttonId={1} activeId={ activeId } /> <Button title={"button 3"} onHover={this.onButtonHover} buttonId={2} activeId={ activeId } /> </div> ); } } ReactDOM.render(<Parent />, app);
.active { background-color: yellow; }
<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> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"></div>
在这里,您有一个可能的仅CSS解决方案: https : //jsfiddle.net/ggcybu71/
.option:hover {
text-decoration: underline;
}
.option:hover:after {
content: "";
display: block;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: -1;
}
这太“ hacky”了,所以我只会将其视为一种好奇,而我可能不会在生产中使用它。 我将改为实施基于Javascript的mousemove事件侦听解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.