实时引用React Material-UI makeStyles中的窗口大小

时间:2019-06-13 06:13:59

标签: reactjs material-ui

Previous question

下面有一些代码,可让我根据窗口大小更改组件的高度。

在重新加载时可以使用,但是我不确定如何实时反映该值。我该怎么办?

更改窗口大小之前 enter image description here

更改窗口大小后
数字已更改,但网格高度(带有棕色背景)仍然相同。 enter image description here

// WindowSizeManager.tsx
import React, { createContext, useContext, ReactNode } from 'react';
import { useWindowSize } from 'react-use';

interface IProps {
  children: ReactNode;
  size?: { width: number; height: number };
}

export const WindowSizeContext = createContext({ width: 0, height: 0 });

const WindowSizeManager = ({ children }: IProps) => {
  const size = useWindowSize();
  return (
    <WindowSizeContext.Provider value={size}>
      {children}
    </WindowSizeContext.Provider>
  );
};

export const useWindowSizeManager = () => {
  return useContext(WindowSizeContext);
};

export default WindowSizeManager;

// SomeComponent.tsx
import React from 'react';
import Container from '@material-ui/core/Container';
import { Grid, makeStyles, Theme, createStyles } from '@material-ui/core';
import { height } from '@material-ui/system';
import { useWindowSizeManager } from './WindowSizemanager';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    screen: {
      margin: 0,
      padding: 0
    },
    surface: {
      backgroundColor: theme.palette.primary.main,
      height: useWindowSizeManager().height - 100,
      fontSize: '48px'
    }
  })
);

const SomeComponent: React.FC = props => {
  const classes = useStyles(props);
  return (
    <Container fixed className={classes.screen}>
      <Grid container className={classes.surface}>
        {useWindowSizeManager().height}
      </Grid>
    </Container>
  );
};

export default SomeComponent;

0 个答案:

没有答案