使用带有 Typescript 的样式化组件,prop 不存在?

Using styled components with Typescript, prop does not exist?

这是我设计的组件。

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;

我收到以下警告:

我怎样才能让它工作?

  • 带样式的组件必须指定要传递给组件的道具,如 styled("h2")<IProps>。您可以从 documentation
  • 阅读更多关于模式的信息
  • css 在这里不是必需的,当你需要从一个函数中实际 return CSS 时,它被添加为一个助手。查看 .

考虑到这些,组件变为:

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

A use-case for css

之前的答案对我有用,但只是为了添加一些对我的情况也有帮助的信息:

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

这意味着您可以创建如下界面:

interface IHeadingStyled {
   emphasized: boolean;
}

并在组件上使用它:

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

(如果你有多个道具,这是实现@BoyWithSilverWings 建议的更简洁的方法)


查看此讨论以获取更完整的信息:

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

在另一个 sheet 中使用样式化组件时,我遇到了同样的错误。

我必须在 index.tsx 中执行此操作:

 export interface RadioBoxProps {
    isActive: boolean;
}

然后,在样式中 sheet:

 import { RadioBoxProps } from "./index";

export const RadioBox = styled.button<RadioBoxProps>`

background: ${(props) => props.isActive ? '#eee' : 'transparent'};

`

在我看的教程中,这个人没有导出界面并在样式中导入就通过了sheet。对他来说,它工作得很好。但是,对我来说,我并没有工作,只是在执行上面显示的操作时才工作。

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

interface ButtonProps {
  width: string;
}

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

或相同的东西不同口味

interface ButtonProps {
  width: string;
}

const Button = styled("button")<ButtonProps>`
  width: ${props => props.width};
`;
   /** In App.tsx **/

      <div className="App">
          <Button>Register</Button>
          <Button primary="primary">Register</Button>
     </div>


    /*In your functional component*/
    import styled from "styled-components";
    
    interface IButtonPropsType {
      primary: string;
    }
    
    export const Button = styled.button<IButtonPropsType>`
    background: ${(props) => (props.primary ? "palevioletred" : "white")}
    color: ${(props) => (props.primary ? "white" : "palevioletred")}
    font-size: 1.5em
    margin: 1em;
    padding: 0.25em 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;
    `;