最初加载页面时,标题应该不可见,但是当用户开始滚动时,标题应该出现。
我期望看到什么?
在用户开始滚动之前,标题是不可见的
我现在看到的东西
页面第一次加载时显示标题,而页面不应该显示。 它只能在Chrome中无法正常使用,并且可以在Safari中运行。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hide: false
};
}
handleHover = () => {
this.setState({
hide: true
});
};
componentDidMount() {
window.addEventListener("scroll", this.handleHover);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleHover);
}
render() {
return (
<div>
{this.state.hide ? (
<div
style={{
width: "100%",
height: "120px",
margin: "0 auto",
position: "absolute"
}}
>
<div
style={{
zIndex: "0",
position: "absolute",
marginLeft: "120px",
marginTop: "6px"
}}
>
<img className="Logo" src={Logo} alt="logo" />
</div>
<div className="menuContainer">
<nav>
<Link to="/" className="linkTitle" href="">
Home
</Link>
<Link to="/shop" className="linkTitle" href="">
Shop
</Link>
<a className="linkTitle" href="#aboutus">
About
</a>
<a className="linkTitle" href="">
Contact Us
</a>
<a className="linkTitle" href="">
As seen
</a>
</nav>
</div>
</div>
) : null}
<div className="picContainer">
<div
style={{ backgroundImage: `url(${hairImage})` }}
className="picSection one"
/>
<div className="picSection two" />
<div className="picSection three" />
<div className="picSection four" />
<div className="picSectionL five" />
</div>
</div>
);
}
}
答案 0 :(得分:2)
https://codesandbox.io/s/zlyqyvjzjl
你去了。确保可以实际滚动。如果div太小而无法滚动,则不会触发该事件。
{this.state.hide ? null : <div>some item</div>}
这是完整的代码:
从“ react”导入React; 从“ react-dom”导入ReactDOM;
导入“ ./styles.css”;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hide: true
};
}
handleHover = () => {
console.log("hello");
this.setState({
hide: false
});
};
componentDidMount() {
window.addEventListener("scroll", this.handleHover);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleHover);
}
render() {
return (
<div style={{ height: "2000px" }}>
{this.state.hide ? null : (
<div
style={{
width: "100%",
height: "120px",
margin: "0 auto",
position: "absolute"
}}
>
<div
style={{
zIndex: "0",
position: "absolute",
marginLeft: "120px",
marginTop: "6px"
}}
>
logo
</div>
</div>
)}
<div className="picContainer">hello</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);