Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

reactjs - Using styled components with Typescript, prop does not exist?

Here is my styled component.

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;

I get warnings that:

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

How can I get this to work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • The styled component will have to specify the prop to pass to the component like styled("h2")<IProps>. You can read more about the pattern from documentation
  • css is not required here, it is added as a helper when you need to actually return CSS from a function. Check out conditional rendering.

Taking these into account, the component becomes:

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

A use-case for css


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...