【问题标题】:How to use forwardedAs prop with styled-components? Using forwardedAs prop with typescript如何将 forwardedAs 道具与样式组件一起使用?将 forwardedAs 道具与打字稿一起使用
【发布时间】:2021-05-02 18:22:31
【问题描述】:

这里是forwardedAs 道具上的文档:https://styled-components.com/docs/api#forwardedas-prop

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

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

我可以通过 ...rest 参数访问 forwardedAs 道具,但我需要为这些道具定义类型,因为我也在使用带有 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}
  />
)

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

  return (
    <a href={forwardAs?.href} {...rest} />
  )
}

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

提前谢谢你。

【问题讨论】:

  • 还有一个额外的问题,我将如何在 Link 组件上定义这个 forwardedAs 道具的类型?

标签: javascript reactjs typescript styled-components react-props


【解决方案1】:

转发为

forwardedAs 属性不适用于传递属性。它实际上是为了将 as 属性传递给链中的下一个项目。考虑这个例子:

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>
);

我们有一个Button,它是一个样式化的组件,我们有一个MyLink,它是另一个样式化的组件,它将其道具向下传递给Button。如果我们想在Button 上设置as 属性,我们可以在MyLink 上设置forwardedAs

使用&lt;MyLink forwardedAs={"div"}&gt;,我们最终渲染到DOM 的元素是div,而不是button,它会应用来自styled HOC 的样式。

传递道具

根据您在此处的示例,实际上不需要 Link 组件。您可以在Button 上设置as="a" 以将其呈现为链接并直接通过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>
);

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2021-03-04
    • 2017-08-15
    • 2017-12-25
    • 2021-02-13
    • 2019-04-18
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多