React не распознает реквизиты, переданные стилевому компоненту в пользовательском интерфейсе материалов. - PullRequest
2 голосов
/ 28 апреля 2020

Styled-component:

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

const Text = styled(Typography)<TextProps>`
  margin-bottom: 10px;
  color: ${({ textColor }) => textColor ?? textColor};
  font-size: ${({ textSize }) => (textSize ? textSize + 'px' : '16px')};
`;

Использование внутри компонента:

<GlobalStyled.Text textColor="green" textSize="20">test</GlobalStyled.Text>

"Предупреждение: React не распознает реквизит textColor для элемента DOM. Если вы намеренно чтобы он отображался в DOM в качестве настраиваемого атрибута, вместо этого пишите его строчными буквами textcolor. Если вы случайно передали его из родительского компонента, удалите его из элемента DOM. "

Реквизиты передаются Typography сам компонент, а не только для стилевого компонента, как обойти это?

ОБНОВЛЕНИЕ

Выпущены стилизованные компоненты 5.1.0: https://github.com/styled-components/styled-components/releases/tag/v5.1.0

Теперь появились новые переходные реквизиты, которые решают эту проблему с помощью фильтрации реквизитов. Вы можете использовать $propsName, знак доллара перед именем вашего реквизита, и он будет передан ТОЛЬКО компоненту Styled!

Ответы [ 2 ]

2 голосов
/ 28 апреля 2020

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

const Text = styled( ({textColor, textSize, ...rest}) => <Typography {...rest}/>)<TextProps>`
  margin-bottom: 10px;
  color: ${({ textColor }) => textColor ?? textColor};
  font-size: ${({ textSize }) => (textSize ? textSize + "px" : "16px")};
`;

Вот рабочий пример (без типа TextProps, но это должно работать): https://codesandbox.io/s/mui-styled-component-removed-props-rfdjx?file= / src / App. js

Вот рабочий пример использования Typescript:

import * as React from "react";

import Typography, {TypographyProps} from '@material-ui/core/Typography';
import {StylesProvider} from '@material-ui/core/styles';
import styled from 'styled-components';

interface TextProps extends TypographyProps {
  textColor: string,
  textSize: number
}

const TypographyWrapper = React.forwardRef<HTMLSpanElement, TextProps>(
  function TypographyWrapper({textColor, textSize, ...other}: TextProps, ref) {
    return <Typography {...other} ref={ref}/>
  }
);
const Text = styled(TypographyWrapper)<TextProps>`
  margin-bottom: 10px;
  color: ${({ textColor }: TextProps) => textColor ?? textColor};
  font-size: ${({ textSize }: TextProps) => (textSize ? textSize + 'px' : '16px')};
`;

export default function App() {
  return <StylesProvider injectFirst>
    <Text textColor="green">Hello World!</Text>
    <Text textColor="red" textSize={30}>Hello World!</Text>
  </StylesProvider>;
}

Edit Remove props that are only for styled-components

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

С версия 5.1.0 , styled-components поддерживает временные реквизиты. Переходные реквизиты не передаются компоненту (т. Е. Просто используются в стилизации) и обозначаются, начиная с имени реквизита $. Это позволяет гораздо проще управлять этим сценарием, для которого больше не требуется компонент-обертка для удаления дополнительных подпорок (как в ответе Декеля).

import * as React from "react";

import Typography, { TypographyProps } from "@material-ui/core/Typography";
import { StylesProvider } from "@material-ui/core/styles";
import styled from "styled-components";

interface TextProps extends TypographyProps {
  $textColor?: string;
  $textSize?: number;
}

const Text: React.FunctionComponent<TextProps> = styled(Typography)`
  margin-bottom: 10px;
  color: ${({ $textColor }: TextProps) => $textColor};
  font-size: ${({ $textSize }: TextProps) =>
    $textSize ? $textSize + "px" : "16px"};
`;

export default function App() {
  return (
    <StylesProvider injectFirst>
      <Text $textColor="green">Hello World!</Text>
      <Text $textColor="red" $textSize={30}>
        Hello World!
      </Text>
    </StylesProvider>
  );
}

Edit Remove props that are only for styled-components

...