简体   繁体   English

React Typescript prop 工作正常,但返回错误

[英]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因为您将一组元素作为子元素传递给Welcome.tsx文件中某处的WelcomeFullscreen组件

If you define your WelcomeFullscreen component as an actual React FunctionComponent, children is always allowed as prop.如果您将WelcomeFullscreen组件定义为实际的 React FunctionComponent,则始终允许children作为 prop。

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

I answered a similar question here: TypeScript error: Property 'children' does not exist on type 'ReactNode' .我在这里回答了一个类似的问题: TypeScript error: Property 'children' doesn't exist on type 'ReactNode'

You probably need to define the type of the component styled by styled-components您可能需要定义由styled-components设置样式的组件的类型

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

Refer: styled-components document of using custom props with typescript参考:使用 typescript 自定义道具的 styled-components 文档

If you are passing custom properties to your styled component it's a good idea to pass type arguments to tagged template如果您将自定义属性传递给样式化组件,最好将类型 arguments 传递给标记模板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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