【问题标题】:React Typescript prop works fine, but returns errorReact Typescript prop 工作正常,但返回错误
【发布时间】:2020-04-14 12:06:43
【问题描述】:

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

组件

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">

错误:

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    因为您将一组元素作为子元素传递给您的 Welcome.tsx 文件某处的 WelcomeFullscreen 组件

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

    const WelcomeFullscreen: React.FC&lt;WelcomeProps&gt; = (props) =&gt; ()...

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

    【讨论】:

      【解决方案2】:

      你可能需要定义styled-components样式的组件类型

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

      参考:using custom props with typescript 的 styled-components 文档

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

      【讨论】:

      • 这有助于混合以下答案。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 2013-03-01
      • 2017-08-16
      • 1970-01-01
      • 2020-07-17
      • 2012-08-28
      • 2020-10-30
      • 1970-01-01
      相关资源
      最近更新 更多