我该如何从React类基础组件中调用钩子调用?

时间:2019-09-17 15:37:02

标签: reactjs material-ui

我想在基于类的组件中使用 useMediaQuery 之类的功能。 我怎样才能做到这一点?

import React from 'react';
import clsx from 'clsx';
import { withStyles ,withTheme ,withMediaQuery } from '@material-ui/styles';
import { useMediaQuery } from '@material-ui/core'

class Main extends React.Component{
    render(){
        const { children ,classes,theme} = this.props;
        const isDesktop = useMediaQuery(theme.breakpoints.up('lg'),{
            defaultMatches :true
        });
        return (
        <div className ={clsx({
            [classes.root] : true,
            [classes.shiftContent] : isDesktop
        })}>
             <main>
                {children}
            </main>
        </div>

        );
    }
}

1 个答案:

答案 0 :(得分:1)

您可以将useMediaQuery和其余逻辑包装在另一个组件中:

const WithClasses = ({ children, theme, classes }) => {
  const isDesktop = useMediaQuery(theme.breakpoints.up("lg"), {
    defaultMatches: true
  });
  return (
    <div
      className={clsx({
        [classes.root]: true,
        [classes.shiftContent]: isDesktop
      })}
    >
      {children}
    </div>
  );
};

然后按如下所示在您的布局中使用它:

class Main extends React.Component {
  render() {
    const { children, classes, theme } = this.props;
    return (
      <WithClasses theme={theme} classes={classes}>
        <main>{children}</main>
      </WithClasses>
    );
  }
}