如何将forwardedAs prop与样式组件一起使用?将forwardedAs 属性与打字稿一起使用

kdi*_*zle 4 javascript typescript reactjs styled-components react-props

forwardedAs以下是prop上的文档: https ://styled-components.com/docs/api#forwardedas-prop 。

正如你所看到的,它不是很详细,也没有展示如何正确使用这个道具。

我的问题是:我如何访问通过 发送下来的道具forwardedAs?我如何定义这些forwardedAs道具的类型?

我可以forwardedAs通过...rest参数访问道具,但我需要为这些道具定义类型,因为我还在 Typescript 中使用样式组件。

这是我的代码示例:

// Button.jsx
const myPropsToForward = {
  href: 'https://somewebsite.com',
  // ...more props
}

const Button = styled.button`
  // ...button styles
`

const myComponent = () => (
  <Button
    as={Link}
    to={ctaLink}
    forwardedAs={myPropsToForward}
  />
)

Run Code Online (Sandbox Code Playgroud)
// Link.jsx
const Link = ({
  forwardedAs,
  ...rest
}) => {
  // How do I access the forwardedAs prop from <Button /> here?

  return (
    <a href={forwardAs?.href} {...rest} />
  )
}
Run Code Online (Sandbox Code Playgroud)

在这里,我需要能够访问Link通过 prop 发送的组件内的 props forwardedAs,但没有关于如何做到这一点的文档。如果我可以访问该forwardedAs道具,我就可以为该Link组件定义正确的类型。我不想依赖该...rest参数,因为我无法为其定义类型。

先感谢您。

Lin*_*ste 7

转发为

forwardedAs道具不是为了传承道具。它实际上是为了将asprop 传递给链中的下一个项目。考虑这个例子:

const Button = styled.button`
  padding: 20px;
`;

const Link = (props: any) => { // not properly typed
  return <Button {...props} />;
};

const MyLink = styled(Link)`
  background-color: blue;
`

const MyComponent = () => (
  <MyLink forwardedAs={"div"}>
    Text
  </MyLink>
);
Run Code Online (Sandbox Code Playgroud)

我们有一个Buttonwhich是一个样式组件,还有一个MyLinkwhich是另一个样式组件,它将它的props向下传递给Button. 如果我们想as在 上设置 prop Button,我们可以设置forwardedAson MyLink

使用<MyLink forwardedAs={"div"}>,我们最终渲染到 DOM 的元素是 adiv而不是 a button,并且它应用了两个 HOC 中的样式styled

传递道具

根据您此处的示例,Link实际上并不需要该组件。您可以将as="a"其设置Button为将其呈现为链接并直接通过myPropsToForward

const myPropsToForward = {
  href: "https://somewebsite.com"
  // ...more props
};

const Button = styled.button`
  background: yellow;
  padding: 20px;
`;

const MyComponent = () => (
  <Button as="a" {...myPropsToForward}>
    Text
  </Button>
);
Run Code Online (Sandbox Code Playgroud)