小编典典

在Typescript中使用样式化的组件,prop不存在吗?

reactjs

这是我的样式化组件。

import * as React from 'react';
import styled from 'styled-components';
import { ComponentChildren } from 'app-types';

interface Props {
    children: ComponentChildren;
    emphasized: boolean;
}

const HeadingStyled = styled.h2`
    ${props => props.emphasized && css`
        display: inline;
        padding-top: 10px;
        padding-right: 30px;
  `}
`;

const Heading = (props: Props) => (
    <HeadingStyled>
        {props.children}
    </HeadingStyled>
);

export default Heading;

我收到以下警告:

  • Property 'emphasized' does not exist on type 'ThemedStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, any>'.
  • Cannot find name 'css'. Did you mean 'CSS'?

我怎样才能使它工作?


阅读 573

收藏
2020-07-22

共1个答案

小编典典

  • 样式化的组件将必须指定prop才能传递给类似的组件styled("h2")<IProps>。您可以从文档中了解有关模式的更多信息
  • css此处不是必需的,当您实际上需要从函数返回CSS时,它将作为帮助程序添加。查看条件渲染

考虑到这些因素,该组件将变为:

const HeadingStyled = styled("h2")<{emphasized: boolean}>`
  ${props => props.emphasized && `
    display: inline;
    padding-top: 10px;
    padding-right: 30px;
  `}
`;

一个用例 css

2020-07-22