当页面最初加载时,标题不应该是可见的,但是当用户开始滚动时,标题应该出现。
我希望看到什么?
在用户开始滚动之前标题不应该可见
我现在看到了什么
标题在页面首次加载时显示,它不应该显示。 它只是在 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>
);
}
}
最佳答案
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);
关于javascript - 损坏的代码?为什么它停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508219/