簡體   English   中英

具有 forwardRef 打字稿錯誤的組件,其中所有道具都應為布爾值

[英]Component with forwardRef typescript error where all props expected to be boolean

我有一個組件,它為我們的應用程序的某些部分形成一個容器,稱為 Box:

interface BoxProps {
  keyId?: number;
  id?: string;
  propsRef?: React.ForwardedRef<HTMLDivElement>;
  span?: number | number[];
  rowSpan?: number | number[];
  center?: boolean;
  textAlign?: string;
  vertAlign?: string;
  transparent?: string;
  bgColor?: string;
  borderColor?: string;
  gridColumnStart?: number;
  gridColumnEnd?: number;
  classList?: string;
  collapsable?: boolean;
  children: React.ReactNode | JSX.Element | Element;
  styleList?: { [key: string]: string };
  title?: string;
  titleTooltip?: string;
  [key: string]: boolean;
}

const Box = forwardRef<HTMLInputElement, BoxProps>(
  (
    props,
    ref
  ) => {
    const {
      keyId,
      id,
      propsRef,
      span,
      rowSpan,
      center,
      textAlign,
      vertAlign,
      transparent,
      bgColor,
      borderColor,
      gridColumnStart,
      gridColumnEnd,
      classList,
      collapsable = false,
      children,
      styleList,
      title,
      titleTooltip
    } = props;

...
return (
<div> stuff </div>

我按照這篇文章來確定如何設置道具: Using a forwardRef component with children in TypeScript

不幸的是,當我嘗試使用這個組件時,我得到了所有道具都應該是布爾值的錯誤:

// REACT
import React from 'react';
import Box from './Box';
import Description from './Description';

const Recommendations = () => {
    return (
        <Box span={3}>
            <Description data="<h3><img class='margin-right padding-light' src='/assets/nn/images/globe.svg'>Recommendation #1</h3>" />
        </Box>
    )
}

export default Recommendations;

錯誤:

webpack compiled with 6 warnings
ERROR in src/components/elements/Recommendations.tsx:8:14
TS2322: Type 'number' is not assignable to type 'boolean'.
     6 | const Recommendations = () => {
     7 |     return (
  >  8 |         <Box span={3}>
       |              ^^^^
     9 |             <Description data="<h3><img class='margin-right padding-light' src='/assets/nn/images/globe.svg'>Recommendation #1</h3>" />
    10 |         </Box>
    11 |     )

ERROR in src/components/elements/Recommendations.tsx:9:13
TS2322: Type 'Element' is not assignable to type 'boolean'.
     7 |     return (
     8 |         <Box span={3}>
  >  9 |             <Description data="<h3><img class='margin-right padding-light' src='/assets/nn/images/globe.svg'>Recommendation #1</h3>" />
       |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    10 |         </Box>
    11 |     )
    12 | }

我究竟做錯了什么?

我期望沒有類型錯誤,它會從 BoxProps 中獲取類型。

一種解決方法是對組件進行類型轉換並手動添加 BoxProps

 as React.ForwardRefExoticComponent<BoxProps & React.RefAttributes<HTMLInputElement>>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM