【问题标题】:How to set type of React Functional Component property to Styled Component `styled.div`?如何将 React 功能组件属性的类型设置为样式化组件`styled.div`?
【发布时间】:2020-11-19 14:25:27
【问题描述】:
import React, { FunctionComponent } from "react"
import styled from "styled-components"

interface ChildProps {
  color: string
}

const Child = styled.div`
  background-color: ${(props: ChildProps) => props.color};
`

interface ParentProps {
  node: FunctionComponent<ChildProps> // How to set node type to Styled Component `styled.div`?
}

const Parent = function(props: ParentProps) {
  const Node = props.node
  return <Node color="white" />
}

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:
    npm install -D @types/styled-components
    
    import styled, { StyledComponent } from "styled-components";
    
    interface ParentProps {
      node: StyledComponent<"div", any, ChildProps, never> 
    }
    

    您可以顺便查找某物的类型,例如在 VSCode 中将鼠标悬停在它上面。


    提示:使用泛型来声明 styled-component 的 props,而不是在函数中声明它。在这种情况下,您可以解构color

    const Child = styled.div<ChildProps>`
      background-color: ${({ color }) => color};
    `
    

    【讨论】:

    • 谢谢艾克!你知道是否有办法使用泛型类型吗?理想情况下,我想避免依赖styled-components,并允许用户将node 属性设置为返回使用ChildProps 类型扩展的div 的任何功能组件。
    猜你喜欢
    • 2021-04-13
    • 2021-04-21
    • 2021-03-08
    • 2019-03-19
    • 2023-01-03
    • 2015-06-26
    • 2018-12-28
    • 2020-09-07
    • 2019-10-09
    相关资源
    最近更新 更多