【问题标题】:TypeScript error passing prop to styled-components将道具传递给样式组件的 TypeScript 错误
【发布时间】:2017-10-20 18:41:27
【问题描述】:

我很难解决这个 TypeScript 问题。

...message: 'Type '{ show: boolean; children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemedOuterStyledProps<HTMLProps<HTMLDiv...'.
  Property 'show' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemedOuterStyledProps<HTMLProps<HTMLDiv...'.'

我正在使用 React + 样式化组件 + TypeScript。如果我有这样的样式组件:

const Component = styled.div`
    opacity: ${props => props.show ? 1 : 0}
`

我的 React 组件看起来像这样:

const ReactComponent = (props: { appLoading: boolean }) => (
  <Component show={appLoading} />
)

我对 TypeScript 很陌生,但我认为我需要在组件上定义 show prop?

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    show 属性指定类型的一种方法可能是这样 -

    const Component = styled.div`
        opacity: ${(props: {show: boolean}) => props.show ? 1 : 0}
    ` 
    

    刚刚在“props: {show: boolean}”中加了()

    【讨论】:

    • 感谢 Mukesh,它需要稍作调整。但它有效:) 我需要包装道具:{show: boolean} with ()
    • 是的,我总是忘记箭头函数 :)
    猜你喜欢
    • 2020-10-28
    • 2021-05-28
    • 1970-01-01
    • 2021-04-05
    • 2019-07-07
    • 1970-01-01
    • 2022-01-24
    • 2019-09-23
    • 2017-08-17
    相关资源
    最近更新 更多