Неспособность применить переопределения пользовательского интерфейса материала в сборнике рассказов в приложении React - PullRequest
1 голос
/ 05 марта 2020

В своем приложении я использую React material-ui и очень полагаюсь на сборники рассказов. Тем не менее, у меня есть некоторые переопределения настроек тем.

Вот настройки:

import { createMuiTheme } from '@material-ui/core/styles';

export const egColorScheme = {
  darkGray: '#494949',
  transparent: 'transparent',
  white: '#FFF',
};

const edvengoFont = {
  fontFamily: "'Montserrat', sans-serif",
};

export const edvengoTheme = createMuiTheme({
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [edvengoFont],
      },
    },
  },
  typography: {
    fontFamily: "'Montserrat', sans-serif",
  },
});

Теперь в некоторых компонентах, когда я создаю сборник рассказов и упаковываю с ThemeProvider, это работает прекрасно. Как в этом компоненте:

import { createStyles, List, ListItem, ListItemIcon, ListItemText, Theme } from '@material-ui/core';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import makeStyles from '@material-ui/core/styles/makeStyles';
import Typography from '@material-ui/core/Typography';
import React from 'react';
import { egColorScheme } from '../../../../utils/styles/edvengo-theme';
import { EgButtonOutlined } from '../EgButton';
import { EmailIcon, PhoneIcon, SkypeIcon } from '../Icons';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    actions: {
      marginTop: '10px',
      paddingBottom: '30px',
      paddingLeft: '30px',
    },
    content: {
      padding: '30px 30px 0',
    },
    itemIcon: {
      minWidth: '16px',
      paddingRight: '11px',
    },
    itemText: {
      color: egColorScheme.darkGray,
      fontSize: '14px',
      fontStyle: 'normal',
      fontWeight: 'normal',
      letterSpacing: '0.02em',
    },
    list: {
      marginTop: '10px',
    },
    root: {
      backgroundColor: egColorScheme.white,
      borderRadius: '10px',
      width: '100%',
    },
    title: {
      color: egColorScheme.darkGray,
      fontSize: '22px',
      fontStyle: 'normal',
      fontWeight: 'bold',
      lineHeight: '27px',
    },
  }),
);

export interface InPageContactBoxProps {
  phone?: string;
  email?: string;
  skype?: string;
  buttonUrl?: string;
}

export const InPageContactBox: React.FC<InPageContactBoxProps> = ({ phone, email, skype, buttonUrl }) => {
  const styles = useStyles();

  return (
    <Card className={styles.root} elevation={0}>
      <CardContent className={styles.content}>
        <Typography gutterBottom variant="h5" component="span" className={styles.title}>
          Contact Us
        </Typography>
        <List className={styles.list}>
          {phone ? (
            <ListItem component={'a'} href={`tel:${phone}`} disableGutters={true}>
              <ListItemIcon className={styles.itemIcon}>
                <PhoneIcon />
              </ListItemIcon>
              <ListItemText className={styles.itemText} primary={phone} />
            </ListItem>
          ) : (
            <></>
          )}
          {email ? (
            <ListItem component={'a'} href={`mailto:${email!}`} target={'_blank'} disableGutters={true}>
              <ListItemIcon className={styles.itemIcon}>
                <EmailIcon />
              </ListItemIcon>
              <ListItemText className={styles.itemText} primary={email} />
            </ListItem>
          ) : (
            <></>
          )}
          {skype ? (
            <ListItem component={'a'} href={`skype:${skype!}?chat`} disableGutters={true}>
              <ListItemIcon className={styles.itemIcon}>
                <SkypeIcon />
              </ListItemIcon>
              <ListItemText className={styles.itemText} primary={skype} />
            </ListItem>
          ) : (
            <></>
          )}
        </List>
      </CardContent>
      <CardActions className={styles.actions}>
        <EgButtonOutlined href={buttonUrl}>Submit Message</EgButtonOutlined>
      </CardActions>
    </Card>
  );
};

И вот его сборник рассказов:

const contactBox = () => (
  <ThemeProvider theme={edvengoTheme}>
    <div style={{ width: '300px', border: '5px solid lightgray', backgroundColor: 'lightgray' }}>
      <InPageContactBox
        phone={text('Phone #', '+1 (778) 668-1811')}
        email={text('Email', 'contact@edvengo.com')}
        skype={text('Skype', 'shurik_a')}
        buttonUrl={text('Button Url', 'http://google.coms')}
      />
    </div>
  </ThemeProvider>
);

storiesOf('Web|Common', module)
  .addDecorator(withKnobs)
  .add('Contact Box', contactBox);

Проблема начинается здесь ...

Один из моих компонентов выглядит следующим образом:

import { createStyles, Paper, Theme } from '@material-ui/core';
import Link from '@material-ui/core/Link';
import makeStyles from '@material-ui/core/styles/makeStyles';
import React from 'react';
import { egColorScheme } from '../../../../utils/styles/edvengo-theme';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      backgroundColor: egColorScheme.white,
      borderRadius: '10px',
      display: 'flex',
      height: '100%',
      overflow: 'hidden',
    },
    title: {
      alignItems: 'center',
      color: egColorScheme.darkGray,
      fontSize: '22px',
      fontStyle: 'normal',
      fontWeight: 'bold',
      lineHeight: '28px',
      padding: '36px 23px',
      textAlign: 'center',
      textDecoration: 'none',
      width: '100%',
    },
  }),
);

export interface TitleBlockProps {
  title: string;
  href?: string;
}

export const TitleBlock: React.FC<TitleBlockProps> = ({ title, href }) => {
  const styles = useStyles();

  return (
    <Paper className={styles.root} elevation={0}>
      <Link className={styles.title} href={href}>
        {title}
      </Link>
    </Paper>
  );
};

со сборником рассказов следующим образом:

import { ThemeProvider } from '@material-ui/core/styles';
import { text, withKnobs } from '@storybook/addon-knobs';
import { storiesOf } from '@storybook/react';
import React from 'react';
import { edvengoTheme } from '../../../../utils/styles/edvengo-theme';
import { TitleBlock } from './TitleBlock';

const titleBlock = () => (
  <ThemeProvider theme={edvengoTheme}>
    <div style={{ width: '300px', border: '5px solid lightgray', backgroundColor: 'lightgray' }}>
      <TitleBlock title={text('Title', 'Ontario')} href={text('Url', 'http://edvengo.com')} />
    </div>
  </ThemeProvider>
);

storiesOf('Web|Common', module)
  .addDecorator(withKnobs)
  .add('Title Block', titleBlock);

По какой-то причине стили из edvengoTheme не применяются. В частности font-family. Что мне здесь не хватает?

1 Ответ

1 голос
/ 14 апреля 2020

Я столкнулся с похожей проблемой, когда моя среда разработки отличалась от версии сборки / развертывания.

Эта статья была полезна для настроек конфигурации с использованием Storybook & Material UI.

Сборник рассказов / MaterialUI / StyledComponents

Короче говоря, некоторые важные настройки сборника рассказов должны включать:

стили-декоратор. js

export const StylesDecorator = storyFn => (
  <ThemeProvider theme={customTheme}>
    <StylesProvider injectFirst>
      {storyFn()}
    </StylesProvider>
  </ThemeProvider>
);

config. js

addDecorator(StylesDecorator)

configure(require.context('../src/stories', true, /\.stories\.js$/), module);

В вашем случае, возможно, вам просто не хватает StyleProvider 'injectFirst' внутри вашего ThemeProvider

...