1

我是 React-Material 主题功能的忠实粉丝,并且已经广泛使用它,但今天我被难住了。要使用主题设置弹出窗口的样式,通常我将弹出窗口(带有display: none)存储在我的主要组件文件中,如下所示:

function App() {

  return (
    <Fragment>
      <Popup /> // ie here
      <LeftPanel />
      <Map />
    </Fragment>
  );
}

然后我的 themeProvider 包装<App/>

<ThemeProvider theme={theme}>
  <App />
</ThemeProvider>

现在我正在尝试设置一个不在内部且不<App/>在加载时 DOM 上的弹出窗口的样式 - 我正在从. 而不是我创建的自定义主题(假设主调色板颜色为绿色),当我尝试访问内部主题时,它使用 MUI 的默认主题(即默认主调色板颜色为紫色)。我尝试从我的文件中导出自定义主题对象并将其直接传递给弹出组件,但它一直使用 MUI 的默认主题,即:const node = document.createElement('div')makeStylescreateMuiThemeindex

弹出按钮,我正在尝试访问我的自定义 MUI 主题:

import React, { FunctionComponent } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';


const useStyles = makeStyles(theme => {
  return {
    text: {
      color: 'white',
      fontSize: theme.typography.pxToRem(14),
    },
    tab: {
      backgroundColor: theme.palette.primary.light
      // This comes back as the default MUI theme :(
    }
  }
});

interface PopupButtonProps { }

export const PopupButton: FunctionComponent<PopupButtonProps> = (props) => {
  const classes = useStyles();
  return (
    <div className={ `${classes.tab} 'custom-popup__view-details pointer'`}>
      <Typography variant='button' classes={{ root: classes.text}}>
        VIEW DETAILS
      </Typography>
    </div>
  );
}

弹出:

const Popup = (props: PopupProps) => {
  const node: HTMLElement = document.createElement('div');

  render(
    <>
      <div className="custom-popup__container">
        <PopupElement text={props.attributes.ServiceName} Icon={ProviderIcon} />
        <PopupElement text={props.attributes.Attribute_1} Icon={AddressIcon} />
        <PopupElement text={props.attributes.Attribute_2} Icon={PhoneIcon} />
      </div>
      <PopupButton />
    </>,
    node
  );
  return node;
}

export default Popup;

有没有人对如何在组件中使用特定主题有任何想法,例如,可能是useTheme将特定自定义主题放入组件的钩子?

Versions:
React: 16.13.1
MUI: 4.9.9 (I'll try upgrading to 4.9.11 in the meantime)
4

1 回答 1

1

就像您使用ThemeProvideraround一样App,您应该使用ThemeProviderin Popup

import theme from "./whereever_you_define_your_theme_using_createMuiTheme";

const Popup = (props: PopupProps) => {
  const node: HTMLElement = document.createElement('div');

  render(
    <ThemeProvider theme={theme}>
      <div className="custom-popup__container">
        <PopupElement text={props.attributes.ServiceName} Icon={ProviderIcon} />
        <PopupElement text={props.attributes.Attribute_1} Icon={AddressIcon} />
        <PopupElement text={props.attributes.Attribute_2} Icon={PhoneIcon} />
      </div>
      <PopupButton />
    </ThemeProvider>,
    node
  );
  return node;
}

export default Popup;
于 2020-04-23T17:02:29.503 回答