TypeScript:为样式化的组件元素扩展 React 组件道具

Posted

技术标签:

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

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

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

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

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

【问题讨论】:

你能告诉我们错误信息吗? 是的,当然,这是一个便于调试的代码框:codesandbox.io/s/cocky-cohen-27cpw 可能和这个问题有关:github.com/DefinitelyTyped/DefinitelyTyped/issues/30451 添加ref?: anyas?: any 将解决类型错误 【参考方案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/… 转发参考 是的!我刚发现! - 感谢您的帮助!

以上是关于TypeScript:为样式化的组件元素扩展 React 组件道具的主要内容,如果未能解决你的问题,请参考以下文章

React 和 Typescript,样式化的组件和子组件

样式化的 MUI 无法在 typescript 中将组件道具传递给 Typography

如何有条件地测试样式化的组件和子元素?

CSS 过渡不适用于反应和样式化的组件

在 React 和 TypeScript 中扩展 HTML 元素,同时保留 props

带有样式组件的 TypeScript