ошибка машинописи компонентов стиля с компонентом Material-UI - PullRequest
0 голосов
/ 04 февраля 2019

Используя машинопись и хотите установить стиль для компонента Material UI с помощью styled-компонентов.
Но ошибка типа происходит с StyledComponent, показывающим Type '{ children: string; }' is missing the following properties

import React, { PureComponent } from 'react';
import styled from 'styled-components'; // ^4.1.3
import { Button } from '@material-ui/core'; // ^3.9.1

class TestForm extends PureComponent {
  render() {
    return (
      <>
        <Button style={{ backgroundColor: 'red' }}>Work</Button>{/* OK  */}

        <StyledButton>Doesn't work</StyledButton>{/* Type Error happens here <=============== */}
        {/**
          Type '{ children: string; }' is missing the following properties from type 'Pick<Pick<(ButtonProps & RefAttributes<Component<ButtonProps, any, any>>) | (ButtonProps & { children?: ReactNode; }), "form" | "style" | "title" | "disabled" | "mini" | ... 279 more ... | "variant"> & Partial<...>, "form" | ... 283 more ... | "variant">': style, classes, className, innerRef [2739]
         */}
      </>
    );
  }
}

const StyledButton = styled(Button)`
  background: blue;
`;

export default TestForm;

Показывает, что пропеллер детей отсутствует.
Я тоже попробовал следующее, но все равно не работает.

const StyledButton = styled(Button)<{ children: string; }>`
  background: blue;
`;

Кто-нибудь знает, как использовать Material UI со стилевыми компонентами в машинописи?

Ответы [ 2 ]

0 голосов
/ 29 апреля 2019

Я также получаю эту ошибку с material-ui v3.9.3 и styled-components v4.2.0 , самыми последними версиями на момент публикации этого ответа.

Мой обходной путь для этого следующий:

import styled from 'styled-components'
import Button, { ButtonProps } from '@material-ui/core/Button'

const StyledButton = styled(Button)`
  background: blue;
` as React.ComponentType<ButtonProps>

Приводит StyledButton к тому же типу, что и UI материала Button.Это устраняет ошибку и дает вам такую ​​же проверку типов, как и для Button.В большинстве случаев это все, что вам нужно.

В случаях, когда вам нужны дополнительные реквизиты для использования в стилях и вы хотите, чтобы они передавались, вы можете просто расширить ButtonProps и привести к этому пользовательскому типу:

type StyledButtonProps = ButtonProps & { background: string }

const StyledButton = styled(Button)`
  background: ${(props: StyledButtonProps) => props.background};
` as React.ComponentType<StyledButtonProps>


const MyComponent = () => (
  <div>
    <StyledButton size='small' background='blue'>one</StyledButton>

    // ERROR HERE - forgot the 'background' prop
    <StyledButton size='small'>two</StyledButton>
  </div>
)
0 голосов
/ 09 февраля 2019

Несколько месяцев назад все работало нормально, но я только начал новый проект, и у меня возникла та же проблема.Должна быть проблема с более свежими версиями.

Ужасно, я знаю, но в то же время, возможно, лучше всего:

const StyledButton: any = styled(Button)`
  background: blue;
`;
...