javascript - 破码?为什么它停止工作
问题描述
当页面最初加载时,标题应该不可见,但是当用户开始滚动时,标题应该出现。
我期望看到什么?
在用户开始滚动之前,标题不应可见
我现在看到了什么
页面首次加载时会显示标题,并且不应该显示。它只是在 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-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 - 用另一个数据集填充数组对象的最佳方法
- excel - Excel等号作为单元格中的第一个字符
- roblox - 检查触发 RemoteEvent 的用户是否在组中,然后继续
- google-apps-script - 错误 抱歉,此时无法打开文件。尝试从 Google 驱动器创建文件时,请检查地址并重试
- unity3d - 如何在 Unity 中分离 Firestore 监听器
- azure-log-analytics - Kubernetes 的 OMS 代理部署到 kube-system 命名空间
- flutter - 如何将Timer的时间转换为分钟
- eclipse - 我在一个 Maven 项目上使用 log4j 1.2.12,但它没有显示“调试”消息。我该如何解决这个问题?
- python - 在 sqlite 和 tkinter 中出现数据不匹配错误
- node.js - Discord Bot 服务器静音