首页 > 解决方案 > 道具不存在?使用 styled-component 和 typeScript,已经实现了 `interface`

问题描述

这是我的样式组件

import React from 'react';
import styled, {css} from 'styled-components';

const CategoryButton = styled(Button).attrs({
  variant: 'outlined',
})`
  ${({ theme }) => css`
    display: flex;
    align-items: center;
    justify-content: center;
    padding: ${theme.spacing(2)}px ${theme.spacing(4)}px;
    background-color: ${(props) =>
      props.selected ? theme.colors.primary.main : theme.colors.background};
    color: ${(props) =>
      props.selected ? theme.colors.background : theme.colors.primary.main};
    border-color: ${(props) =>
      props.selected ? theme.colors.primary.main : '#c8c8c8'};
  `}
`;

它返回一个错误说

我已尝试实施有关此其他问题的建议,以指定要传递给组件的道具

interface CategoryButton {
  selected?: boolean;
}

const CategoryButton = styled(Button).attrs({
  variant: 'outlined',
})<CategoryButton>`
  ${({ theme }) => css`
    ...
  `}
`;

尽管如此,同样的错误仍然出现。我怎样才能让它工作?

标签: reactjstypescriptstyled-components

解决方案


你必须像这样selected进入。CategoryButton 它与传递给孩子的道具相同:

<CategoryButton selected={true}/>

推荐阅读