在React Material-UI makeStyles中引用窗口大小

时间:2019-06-12 23:00:41

标签: reactjs material-ui

当我为一个组件创建自定义样式时,我将拥有一个类似const的

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    screen: {
      margin: 0,
      padding: 0
    },
    surface: {
      backgroundColor: theme.palette.primary.main,
      height: // use windowSize here
    }
  })
);

,然后在功能组件中执行此操作:

const windowSize = useWindowSize(); // { width:number, height:number }
const classes = useStyles();
return (
<Container fixed className={classes.screen}>
  <Grid container className={classes.surface}>
    <br />
  </Grid>
</Container>

当我想参考窗口大小(例如,窗口高度)时,我可以写

  <Grid container className={classes.surface} height="75%">

但是不可能将该信息包含在makeStyles中并计算数字,例如与calc(100vw - 100px)等效吗?
如果我将calc直接写在makeStyles中,将无法正常工作。

我找到了一个库react-use,钩子useWindowSize可以处理此问题,但是不确定是否可以解决。除了使用height属性,我没有办法吗?

1 个答案:

答案 0 :(得分:0)

此方法部分有效,尽管在调整屏幕大小(需要重新加载)时不会实时更新高度。

参考:https://github.com/pdeona/responsive-layout-hooks

下一个问题:Referring to window size in React Material-UI makeStyles in real time

// 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
    }
  })
);

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;