所以基本上当我将鼠标悬停在"驾驶"选项是一个h1,我想要一个div容器出现,其中包含其他几个详细选项。然后如果我点击"骑"选项是另一个h1,我想要一个div出现,有更多的细节和选项。一次只能选择一个,无论是乘坐/驾驶,但是如果我将鼠标悬停在骑行上,那么出现的div需要保持到鼠标离开div为止,如果我将鼠标悬停在驱动器上,则需要出现驱动器div 。希望你们能帮忙!这是我的代码
import React, { Component } from 'react';
import './App.css';
class Header extends Component {
render() {
return (
<div className="Nav">
<header className="Nav-header">
<h1 className="Nav-title">Halcon</h1>
<p className="Nav-drive"><a href="*" className="Nav-link" onMouseEnter={this.mouseOver.bind(this)} onMouseLeave={this.mouseOut.bind(this)}>Drive</a></p>
<p className="Nav-seperator">|</p>
<p className="Nav-ride"><a href="*" className="Nav-link">Ride</a></p>
</header>
// Div i want to appear if Drive is hovered
<div className="Drive-toggle">
<h3>Why drive with us?</h3>
<h3>Safety</h3>
<h3>Requirements to Drive</h3>
<h3>Driver App</h3>
<h3>Driver - Log In</h3>
</div>
// Div i want to appear if Ride is hovered
<div className="Ride-toggle">
<h3>Why drive with us?</h3>
<h3>Safety</h3>
<h3>Requirements to Drive</h3>
<h3>Driver App</h3>
<h3>Driver - Log In</h3>
</div>
</div>
);
}
}
export default Header;
答案 0 :(得分:6)
您可以使用state
存储布尔值hovered
,并使用onMouseEnter
和onMouseLeave
更新state
。
然后你可以render
一个样式,一个CSS
类或一个组件conditionally。
这是一个小例子:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hovered: false
};
}
onMouseEnter = e => {
this.setState({ hovered: true });
};
onMouseLeave = e => {
this.setState({ hovered: false });
};
render() {
const { hovered } = this.state;
const style = hovered ? { backgroundColor: "#333", color: "#fff" } : {};
return (
<div>
<div onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}>
Hover over me!
</div>
<hr />
<div style={style}>Was it hovered?</div>
<hr />
{hovered && <div>Yes!!</div>}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>