首页 > 解决方案 > 如何将 React 功能组件属性的类型设置为样式化组件`styled.div`?

问题描述

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

标签: reactjstypescriptstyled-components

解决方案


npm install -D @types/styled-components
import styled, { StyledComponent } from "styled-components";

interface ParentProps {
  node: StyledComponent<"div", any, ChildProps, never> 
}

顺便说一句,您可以通过在 VSCode 中将鼠标悬停在某事物上来查找某事物的类型。


提示:使用泛型来声明样式组件的道具,而不是在函数中声明它。在这种情况下,您可以解构color.

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

推荐阅读