繁体   English   中英

如何在 Typescript 上为传播道具声明类型

[英]How to declare types on Typescript for spread props

我想弄清楚如何让这个代码在 TypeScript 上工作

type ScrollProps = {
  autoHide: boolean
  autoHideTimeout: number
  autoHideDuration: number
}

const renderThumb = ({ style, ...props}) => {
  const thumbStyle = {
    borderRadius: 6,
    backgroundColor: 'rgba(35, 49, 86, 0.8)'
  }
  return <div style={{ ...style, ...thumbStyle }} {...props} />
}

const CustomScrollbars = (props: ScrollProps) => (
  <Scrollbars
    renderThumbHorizontal={renderThumb}
    renderThumbVertical={renderThumb}
    {...props}
  />
)

...
<CustomScrollbars autoHide autoHideTimeout={500} autoHideDuration={200}>
 ...
</CustomScrollbars>

如果我为 CustomScrollbars 上的道具创建一个类型,我会在<CustomScrollbars>上收到错误,如果我没有在 CustomScrollbars function 上的道具上收到错误。

我在style上也遇到错误,它想知道什么类型,但我不知道该放什么类型。

为什么隐式any不起作用,我怎样才能让这个代码在 TypeScript 上工作?

https://codesandbox.io/s/react-hooks-with-typescript-forked-8g5g6

老实说, react-custom-scrollbars package 的类型确实很缺乏。 renderThumbHorizontalrenderThumbVertical道具的预期类型被声明为React.StatelessComponent<any> - 一个接受any道具的组件。 所以我不知道将调用这些组件的道具是否与您的renderThumb期望的道具匹配。

至于为renderThumb声明 props(我建议大写,因为如果您尝试在 JSX 中使用它会产生问题,例如<renderThumb /> ),传播运算符并不重要。 您正在接受 object 的道具,并且所有这些道具都被传递给div 所以我们想要接受div可以接受的任何道具。 该类型是JSX.IntrinsicElements['div']

有了这个定义, style是类型React.CSSProperties | undefined React.CSSProperties | undefined 传播undefined实际上是可以的,因此您不需要要求style或设置默认值。

const RenderThumb = ({ style, ...props}: JSX.IntrinsicElements['div']) => {
  const thumbStyle = {
    borderRadius: 6,
    backgroundColor: 'rgba(35, 49, 86, 0.8)'
  }
  return <div style={{ ...style, ...thumbStyle }} {...props} />
}

至于CustomScrollbars ,您可以从 package 导入道具,而不必自己重新定义它们。 如果您将组件键入为React.FunctionComponent<Props> ,它将自动包含children道具。 (但是您的 CodeSandbox 有一些问题,因为它找不到那种类型)。

import React from "react";
import { Scrollbars, ScrollbarProps } from "react-custom-scrollbars";

const CustomScrollbars: React.FC<ScrollbarProps> = (props) => (
  <Scrollbars
    renderThumbHorizontal={renderThumb}
    renderThumbVertical={renderThumb}
    {...props}
  />
);

我认为您需要将children添加到道具类型中。

对于样式,添加以下类型

const renderThumb = ({ style, ...props}: {style: React.CSSProperties}) => {
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM