我想创建一个按钮,其样式在悬停时发生变化,并保持这种状态直到另一个悬停发生。从本质上讲,我想创建一个按钮,其焦点通过悬停更改,如here所示。我想我可以通过改变父和子之间状态的一些函数来做到这一点,但有没有更简单的方法呢?感谢。
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>
答案 0 :(得分:1)
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>
答案 1 :(得分:0)
这里有一个可能的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事件监听解决方案。