【问题标题】:TypeScript: Extend React component props for styled component elementTypeScript:为样式化的组件元素扩展 React 组件道具
【发布时间】:2019-12-16 21:16:35
【问题描述】:

我正在尝试在 TypeScript 中扩展一个反应组件道具,以便它包含所有正常的 html 按钮 attributes,以及反应特定的东西,如 ref

我的理解是React.HTMLProps这个类型是我需要的,(React.HTMLAttributes不包含ref

但是,当尝试将我的 props 传递给 styled 组件时,编译器会报错。

我的尝试??????????代码沙盒示例:https://codesandbox.io/s/cocky-cohen-27cpw

【问题讨论】:

标签: javascript reactjs typescript styled-components


【解决方案1】:

几件事。

将输入改为:

interface Props extends React.ComponentPropsWithoutRef<'button'> {
  loading?: boolean
  secondary?: boolean
  fullWidth?: boolean
}

这应该可以为您解决问题。我分叉了你的沙箱,它消除了错误。

还有一个你可以使用的 SO 帖子:Using a forwardRef component with children in TypeScript - 答案详细说明了一种方式,但也提到了答案 1。

【讨论】:

    【解决方案2】:

    感谢所有帮助我查明真相的人。我真正需要的是能够将 refs 转发到我的底层样式组件,我在 TypeScript 中实现了这一点,如下所示:

    【讨论】:

      【解决方案3】:

      您使用了错误的属性,SButton 无法访问参考。

      import React, { ButtonHTMLAttributes, DetailedHTMLProps } from "react";
      import { render } from "react-dom";
      import styled, { css } from "styled-components";
      
      interface Props extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
        loading?: boolean;
        secondary?: boolean;
        fullWidth?: boolean;
      }
      
      export const Button: React.FC<Props> = p => {
        const { ref, ...buttonProps } = p;
        return <SButton {...buttonProps}>{p.children}</SButton>;
      };
      
      export const SButton = styled.button<Props>(
        p => css`
          /*  */
        `
      );
      
      render(<Button>Hello world</Button>, document.getElementById("root"));
      

      这会为您的道具使用正确的 ButtonHTMLAttributes。 SButton 不接受 ref,这就是为什么它从带有 const { ref, ...buttonProps } = p; 的按钮道具中提取的原因。这将使 buttonProps 将 p 中的所有内容都保留下来,除了 ref。 希望这会有所帮助。

      【讨论】:

      • 事情是我想将潜在的参考传递给按钮元素。我想知道这样的事情有多正确 ``` interface Props extends React.HTMLAttributes { loading?: boolean secondary?: boolean fullWidth?: boolean children: React.ReactNode className?: string ref?: React.Ref } ```
      • 查看reactjs.org/docs/… 转发参考
      • 是的!我刚发现! - 感谢您的帮助!
      猜你喜欢
      • 2021-01-13
      • 1970-01-01
      • 2020-01-09
      • 2021-01-26
      • 2021-05-10
      • 2021-12-13
      • 2019-03-03
      • 2021-09-29
      • 2018-10-09
      相关资源
      最近更新 更多