【发布时间】:2020-08-09 00:32:26
【问题描述】:
我正在尝试获取页面的完整高度以将其应用于样式,特别是darkMask 类。
我需要高度,因为当我在页眉内执行操作时,整个页面都会应用一个深色层,但调用该操作后出现的元素除外。
现在,由于 useRef 钩子,我得到了高度,然后我把它放到了容器中,但这并没有给我完整的高度
import { useContext, useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/router';
import { Header } from '../Header';
import { SearchToggleContext } from '../../contexts/SearchToggleContext';
import styles, { globalStyles } from './styles';
export const Layout = ({ children }) => {
const [height, setHeight] = useState();
const mainContainer = useRef(null);
const { isOpenSearch } = useContext(SearchToggleContext);
const router = useRouter();
useEffect(() => {
if (mainContainer.current) {
setHeight(mainContainer.current.offsetHeight);
}
}, [router]);
return (
<>
<div className='darkMask' />
<Header />
<main ref={mainContainer}>{children}</main>
<style jsx global>
{globalStyles}
</style>
<style jsx>{styles}</style>
<style jsx>{`
.darkMask {
display: ${isOpenSearch ? 'block' : 'none'};
height: ${height}px;
}
`}</style>
</>
);
};
/* Styles of layout */
import css from 'styled-jsx/css';
export const globalStyles = css.global`
html,
body {
height: 100%;
width: 100%;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
.navbarItem {
margin-right: 2em;
}
`;
export default css`
main {
height: calc(100vh - 80px);
width: 100%;
top: 80px;
position: absolute;
}
.darkMask {
position: relative;
z-index: 4;
width: 100%;
top: 80px;
position: absolute;
background-color: rgba(45, 45, 45, 0.9);
}
`;
/* _app.js file */
import { Layout } from '../components/Layout';
import { SearchToggleContextProvider } from '../contexts/SearchToggleContext';
function MyApp({ Component, pageProps }) {
return (
<>
<SearchToggleContextProvider>
<Layout>
<Component {...pageProps} />
</Layout>
</SearchToggleContextProvider>
</>
);
}
export default MyApp;
【问题讨论】:
标签: javascript reactjs next.js server-side-rendering