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

时间:2020-04-14 12:06:43

标签: javascript reactjs typescript

我创建了组件,然后将props传递给样式化的组件,它可以正常工作,但是一开始它总是会出现此错误。

组件

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>
);

用法:

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

错误: enter image description here

2 个答案:

答案 0 :(得分:2)

因为您要将某个元素元素数组作为子元素传递到WelcomeFullscreen文件中的Welcome.tsx组件中,所以

如果您将WelcomeFullscreen组件定义为实际的React FunctionComponent,则始终允许children作为道具。

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

我在这里回答了类似的问题:TypeScript error: Property 'children' does not exist on type 'ReactNode'

答案 1 :(得分:1)

您可能需要定义由styled-components设置样式的组件的类型

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

引用:using custom props with typescript的样式组件文档

如果要将自定义属性传递给样式化的组件,则最好将类型参数传递给标记的模板