当使用函数作为组件时,您可以使用material-ui 中的useMediaQuery
钩子(Hook)。但是它没有向您展示如何在类中使用此 Hook 。
所以我做了一些研究,发现你可以通过这样做在类里面使用它:
import React from 'react';
import useMediaQuery from '@material-ui/core/useMediaQuery';
const withMediaQuery = (...args) => Component => props => {
const mediaQuery = useMediaQuery(...args);
return <Component mediaQuery={mediaQuery} {...props} />;
};
export default withMediaQuery;
但是,当将其添加到类中时,如下所示:
export default withStyles(styles)(withMediaQuery(Main));
它给了我这个错误:
index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
我确实需要使用媒体查询,因为有些变量依赖于它们。这是我想使用媒体查询的类的渲染方法。
render() {
const { classes, children } = this.props;
const isDesktop = useMediaQuery(theme => theme.breakpoints.up('lg'), {
defaultMatches: true,
});
const shouldOpenSidebar = isDesktop ? true : this.state.openSidebar;
return (
<div
className={cc({
[classes.root]: true,
[classes.shiftContent]: isDesktop,
})}>
<Topbar
onSidebarOpen={this.handleSidebarOpen}
/>
<Sidebar
onClose={this.handleSidebarClose}
open={shouldOpenSidebar}
variant={isDesktop ? 'persistent' : 'temporary'}
/>
<main className={classes.content}>
{children}
</main>
</div>
);
}
我已经尝试包装组件,但随后我将无法使用变量
最佳答案
您没有提供 useMediaQuery
所需的 args
,因此 Main
作为 args
传递,并返回一个期望该组件的函数。当 React 尝试渲染(调用函数)时,返回值是另一个函数,它不是作为 React 子级的值。
调用函数 - withMediaQuery
并向其传递媒体查询,然后将 Main
传递给返回的函数。
示例:
export default withStyles(styles)(withMediaQuery('(min-width:600px)')(Main));
关于javascript - 如何在类组件中使用useMediaQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59672212/