programing

고정 AppBar 아래의 콘텐츠

lastcode 2023. 2. 13. 20:32
반응형

고정 AppBar 아래의 콘텐츠

기본적인 질문일 것입니다만, 문서에서는 예를 찾을 수 없었습니다.사용.material-ui-next 베타.30.다음과 같은 것이 있습니다.

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as mui from 'material-ui';
import 'typeface-roboto';

function App() {
  return (
    <div>
      <mui.Reboot />
      <mui.AppBar color="primary" position="fixed">
        <mui.Toolbar>
          <mui.Typography color="inherit" type="title">
            My Title
          </mui.Typography>
        </mui.Toolbar>
      </mui.AppBar>
      <mui.Paper>
        My Content
      </mui.Paper>
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

그리고 나는 그mui.Paper콘텐츠는 AppBar 아래에 표시되며 AppBar에 의해 숨겨지지 않습니다.어디 빠진 부품이라도 있나요?

그냥 사용하다position="sticky"대신position="fixed"앱바에 접속합니다.

콘텐츠는 화면에는 표시되지만,AppBar를 사용할 수 있습니다.theme.mixins.toolbar앱 바 높이에 대한 정보를 로드하고 그에 따라 콘텐츠를 이동하려면:

const styles = theme => ({
  // Load app bar information from the theme
  toolbar: theme.mixins.toolbar,
});

그런 다음 다음,div콘텐츠 상위에 있는 콘텐츠에 따라 콘텐츠를 변경합니다.

<Paper>
  <div className={classes.toolbar} />
    MyContent will be shifted downwards by the div above. If you remove 
    the div, your content will disappear under the app bar.
</Paper>

여기서 일어나고 있는 일은theme.mixins.toolbar에 대한 정보를 로드하고 있습니다.AppBar디멘션으로 표현합니다.그런 다음 해당 정보를 에 적용합니다.div사이징을 하다div콘텐츠를 화면 아래로 이동하기에 딱 맞는 높이입니다.

다음은 완전한 작업 예를 제시하겠습니다.

import React from 'react';
import Paper from 'material-ui/Paper';
import Reboot from 'material-ui/Reboot';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import { withStyles } from 'material-ui/styles';

const styles = (theme) => ({
  toolbar: theme.mixins.toolbar,
});

const App = (props) => {
  const { classes } = props;

  return (
    <div>
      <Reboot />
      <AppBar color="primary" position="fixed">
        <Toolbar>
          <Typography color="inherit" type="title">
            My Title
          </Typography>
        </Toolbar>
      </AppBar>
      <Paper>
        <div className={classes.toolbar} />
        MyContent will be shifted downwards by the div above. If you remove 
        the div, your content will disappear under the app bar.
      </Paper>
    </div>
  );
}

export default withStyles(styles)(App);

AppBar 툴바를 추가합니다.

<AppBar>
  <Toolbar>
    ...toolbar content...
  </Toolbar>
</AppBar>

<Toolbar /> // <- does the trick

출처 : https://github.com/mui-org/material-ui/issues/16844#issuecomment-517205129

앱 표시줄 상승 예제는 빈칸만 추가합니다.Toolbar:

export default function ElevateAppBar(props) {
  return (
    <React.Fragment>
      <CssBaseline />
      <ElevationScroll {...props}>
        <AppBar>
          <Toolbar>
            <Typography variant="h6">Scroll to Elevate App Bar</Typography>
          </Toolbar>
        </AppBar>
      </ElevationScroll>
      <Toolbar />  // <-- The important part.
      <Container>
        <Box my={2}>
          {[...new Array(12)]
            .map(
              () => `Cras mattis consectetur purus sit amet fermentum.
Cras justo odio, dapibus ac facilisis in, egestas eget quam.
Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et.`,
            )
            .join('\n')}
        </Box>
      </Container>
    </React.Fragment>
  );
}

이 솔루션들 중 어느 것도 나에게는 전혀 효과가 없었다.

창의 AppBar 크기가 모바일로 변경(960px)됩니다.theme.mixins.toolbar솔루션이 정적 테마 높이를 반환하므로 AppBar 아래에 여유 공간이 남아 있습니다.position="sticky"솔루션은 AppBar를 인라인으로 배치하여 페이지 맨 위에 있지 않으면 액세스할 수 없게 합니다.

저의 솔루션은 다음과 같습니다.

export default function () {
  const nav = useRef();
  const [navHeight, setNavHeight] = useState(0);
  const [isMobile, setMobile] = useState(false);

  useLayoutEffect(() => {
    nav.current && setNavHeight(nav.current.clientHeight);
  }, [isMobile]);

  const checkIsMobile = () => (window.innerWidth < 960 ? true : false);
  if (typeof window !== 'undefined') {
    window.onresize = () => isMobile !== checkIsMobile && setMobile(checkIsMobile);
  } 

  return (
    <>
      <AppBar ref={nav}></AppBar>
      <div style={{ paddingTop: `${navHeight}px`}} />
    </>
  )
}

useLayoutEffect 후크는 window.innerWidth가 임계값인 960px를 초과하면 기동되며 setNavHeight가 트리거됩니다.이거는 더미의 paddingTop 설정에 사용됩니다.<div/>아래쪽에<AppBar/>.

이 솔루션은 2020/06/31 현재 Material-UI 4.11.0 및 Next.js 9.4.4에서 작동합니다.

이 질문은 고정 앱바 아래에 있는 "콘텐츠"에 대한 것입니다.컨텐츠가 페이지의 맨 위에만 있는 경우, 위의 답변은 모두 유효하지만, 컨텐츠가 링크 앵커와 ID, 머리글 등의 요소에 스크롤하는 것도 의미한다면...이는 대부분의 페이지에서 거의 공통적으로 볼 수 있는 것으로, 어느 쪽의 솔루션도 만족스러운 것은 아닙니다.CSS는 다음과 같은 문제를 잘 해결합니다.scroll-padding-top:

html {
    scroll-padding-top: 80px;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-top

언급URL : https://stackoverflow.com/questions/48508449/content-beneath-fixed-appbar

반응형