如何在React Typescript中实现轮播

问题描述 投票:0回答:2

我在react js中实现了

react-responsive-carousel
https://www.npmjs.com/package/react-responsive-carousel,工作正常。我需要转换成 React TypeScript。我引入了 IResarousel 接口,其中定义了子项并设置属性,但出现错误。

error

 Type 'ReactNode[] | undefined' is not assignable to type 'ReactChild[] | undefined'.
 Type 'ReactNode[]' is not assignable to type 'ReactChild[]'.
 Type 'ReactNode' is not assignable to type 'ReactChild'.
 Type 'undefined' is not assignable to type 'ReactChild'.ts(2322)
 types.d.ts(21, 5): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Carousel> & Pick<Readonly<CarouselProps>, never> & InexactPartial<...> & InexactPartial<...>'
 (parameter) children: React.ReactNode[] | undefined

IResarousel

interface IResarousel {
  children?: React.ReactNode[];
  settings: object;
}

export default IResarousel;

Resarousel.tsx

import React from 'react';
import { Carousel } from "react-responsive-carousel";
import IResarousel from '../../../interfaces/UI/IResarousel';

function Resarousel({children, settings} :IResarousel) {
  return (
    <Carousel {...settings}>
        {children} 
    </Carousel>
 );
}

export default Resarousel;

以下模型作为 .js 文件可以正常工作

import React from 'react';
import { Carousel } from "react-responsive-carousel";

function Resarousel({children, settings}) {
  return (
       <Carousel {...settings}>
        {children} 
      </Carousel>
);
}

 export default Resarousel;
carousel react-typescript
2个回答
0
投票

使用 TypeScript 时,建议使用

PropsWithChildren<Props>
辅助类型。

从道具界面中删除

children
属性,然后使用:

function Resarousel({children, settings} :PropsWithChildren<IResarousel>) {
  // [...]
}

0
投票
Carousel 组件的 Children 属性需要一组

React.ReactChild 元素。但在您的界面中,children 属性定义为 React.ReactNode 元素的数组。 请参阅react-responsive-carousel github存储库中的类型:https://github.com/leandrowd/react-responsive-carousel/blob/master/src/components/Carousel/types.ts

更改您的界面如下:

interface IResarousel { children?: React.ReactChild[]; settings: object; }
    
© www.soinside.com 2019 - 2024. All rights reserved.