在打字稿中,我可以将 JSX.Element 作为道具传递给样式组件吗?

In typescript, can I pass JSX.Element as props to styled-components?

注意:请注意我的英语很差

这是一个组件,它以父元素为道具,并在鼠标悬停时显示标注:

const Explanation = styled.span`
  // Detailed implementation is omitted.
  ${(props) => props.parent}:hover & {
    display: inline;
  }
`;

// Examples of Use
<MyButton>Button<Explanation parent={MyButton}>It's MyButton</Explanation></MyButton>

<MyDiv>Div<Explanation parent={MyDiv}>It's MyDiv</Explanation></MyDiv>

将其迁移到打字稿时,我在 props.parent 部分收到 ts(2345) 错误。

const Explanation = styled.span<{parent: JSX.Element}>`
  // Detailed implementation is omitted.
  ${(props) => props.parent}:hover & {
    display: inline;
  }
`;

是否可以在 typescript 中将 JSX.Element 作为 props 传递?

那是因为 Parent 不是常规的 JSX 元素而是 StyledComponent 所以你可以声明

import styled, {StyledComponent} from "styled-components";

const Explanation = styled.span<{ parent: StyledComponent<"div", any, {}, never> }>`

来匹配 Parent 类型,但不是显式声明它,您可以将 Parent 的类型与 typeof.

一起使用
const Explanation = styled.span<{ parent: typeof Parent }>`

https://codesandbox.io/s/awesome-smoke-ztmcv3?file=/src/App.tsx