简体   繁体   中英

React Typescript prop works fine, but returns error

I created component and I'm passing props to styled components, it works fine, but at first prop it always get this error.

Component

type WelcomeProps = { 
    image: String,
    color: String
}

const StyledWelcome = styled.section`
    width: 100vw;
    height: 100vh;
    background-color: ${props => props.color};
    background: ${props => `url(${props.image}) no-repeat center`};
    display: flex;
    flex-direction: column;
    justify-content: center;
`


const WelcomeContainer = styled.div`
    width: 1350px;
    margin: 0 auto;
`

export const WelcomeFullscreen = (props: WelcomeProps) => (
    <StyledWelcome image={props.image} color={props.color}>
        <WelcomeContainer/>
    </StyledWelcome>
);

Usage:

<WelcomeFullscreen image={HomepageImage} color="#000">

Error: 在此处输入图像描述

Because you're passing an array of elements as children to your WelcomeFullscreen components in your Welcome.tsx file somewhere

If you define your WelcomeFullscreen component as an actual React FunctionComponent, children is always allowed as prop.

const WelcomeFullscreen: React.FC<WelcomeProps> = (props) => ()...

I answered a similar question here: TypeScript error: Property 'children' does not exist on type 'ReactNode' .

You probably need to define the type of the component styled by styled-components

const StyledWelcome = styled(div)<WelcomeProps>`
  ...
`

Refer: styled-components document of using custom props with typescript

If you are passing custom properties to your styled component it's a good idea to pass type arguments to tagged template

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM