简体   繁体   English

如何使样式化的 ReacJs Header 组件具有粘性或固定在顶部?

[英]How to make an styled ReacJs Header component sticky or fixed on top?

So I have a problem with my Header, I want it to be fixed on top while the page is being scrolled down, that's the Header component:所以我的 Header 有问题,我希望在向下滚动页面时将其固定在顶部,这就是 Header 组件:

As seen on the code, I've already tried to use "position = fixed" , but then my header got resized, then I've tried to set it's width like "width = "100%"" but it over sized the page如代码所示,我已经尝试使用"position = fixed" ,但后来我的 header 调整了大小,然后我尝试将其宽度设置为"width = "100%""但它超出了页面大小

import { makeStyles } from "@material-ui/core/styles";
import { Grid, Typography } from "@material-ui/core";
import { withRouter } from "react-router-dom";


const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.primary,
    backgroundColor: "#ffeb3b",
    boxShadow: "1px 1px 1px 1px",
    position: "fixed",
  },
  header: {
    backgroundColor: "#4c4c4c",
    color: theme.palette.text.primary,
    flexGrow: 1,
    padding: theme.spacing(2),
    // position: "fixed",
    // minWidth: "100%"
  },
  spacing: {
    marginHorizontal: theme.spacing(2)
  },
  loginName: {
    maxWidth: "20%",
    fontSize: 16,
    fontWeight: "bold"
  },
  title: {
    fontFamily: "Flama medium",
    color: "#FFFFFF",
    fontSize: '1.5rem',
    [theme.breakpoints.down('xs')]: {
      fontSize: '1.18rem',
      maxWidth: 190,
    },
    [theme.breakpoints.up('md')]: {
      fontSize: '1.75rem',
    },
  }
}));

const Header = props => {
  const classes = useStyles();

  return (
    <div className={classes.header} id="some">
      <Grid
        container
        direction="row"
        justify="space-between"
        alignItems="center"
      >
        <Grid >{props.leftIcon}</Grid>
        <Grid >
          <Typography align="center" variant="h5" component="p" className={classes.title}>{props.title}</Typography>
        </Grid>


        <Grid >{props.rightIcon}</Grid>
        {props.rightIconAfter ? <Grid item>{props.rightIconAfter}</Grid> : ""}
      </Grid>
    </div>
  );
};

export default withRouter(Header);

Try adding position: fixed and width: 100vw in your header尝试在 header 中添加 position: fixed and width: 100vw

Like so:像这样:

header: {
    backgroundColor: "#4c4c4c",
    color: theme.palette.text.primary,
    flexGrow: 1,
    padding: theme.spacing(2),
    position: "fixed",
    width: "100vw"
  },

在此处输入图像描述

If you see the image, I scrolled it a bit but the position of the header is fixed and occupies the full screen如果您看到图像,我将其滚动了一下,但 header 的 position 是固定的并占据全屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM