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

use*_*776 13 typescript reactjs styled-components

这是我的样式化组件。

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;
Run Code Online (Sandbox Code Playgroud)

我收到以下警告:

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

我该如何工作?

Agn*_*ney 18

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

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

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

一个用例 css


Bru*_*iro 8

The previous answer worked for me, but just to add some information that was also helpful in my case:

StyledComponents uses a "ThemedStyledFunction" interface that allows the user to define additional Prop Types.

That means you could create an interface like:

interface IHeadingStyled {
   emphasized: boolean;
}
Run Code Online (Sandbox Code Playgroud)

And use it on the component:

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

(Which is a cleaner way to implement what @BoyWithSilverWings suggested, in case you have multiple props)


Check this discussion for more complete information:

https://github.com/styled-components/styled-components/issues/1428#issuecomment-358621605


ncu*_*ica 6

这个解决方案也适用于情感,也许是因为他们都使用手写笔作为预处理器?

interface ButtonProps {
  width: string;
}

const Button = styled("button")<ButtonProps>((props) => {
  return `width: ${props.width};`;
});
Run Code Online (Sandbox Code Playgroud)

或相同的东西不同的味道

interface ButtonProps {
  width: string;
}

const Button = styled("button")<ButtonProps>`
  width: ${props => props.width};
`;
Run Code Online (Sandbox Code Playgroud)

或者

interface ButtonProps {
  width: string;
}

const Button = styled.button<ButtonProps>`
  width: ${props => props.width};
`;
Run Code Online (Sandbox Code Playgroud)