我对 Typescript 比较陌生并且已经恋爱了,但是我现在面临一个奇怪的问题:
我在父组件中创建了一个字符串数组,将其作为道具传递给子组件,并尝试从那里访问带有编号索引的数组。
这是我得到的编译错误:
/home/simon/development/portfolio/src/components/Projects/ImageSlider/ImageSlider.tsx(27,23) 中的 TypeScript 错误:元素隐式具有“任何”类型,因为“0”类型的表达式不能用于索引类型“PropsWithChildren”。“PropsWithChildren”类型上不存在属性“0”。TS7053
ImageSlider.tsx(子)
import React, { useEffect, useState } from "react";
import styles from "./ImageSlider.module.scss";
import { motion } from "framer-motion";
import Modal from "react-modal";
interface ImageSliderProps {
images: string[];
}
const ImageSlider: React.FC<ImageSliderProps> = (images) => {
const [index, setIndex] = useState<number>(0);
const slideRight = () => { };
const slideLeft = () => { };
return (
<div className={styles.slider_wrapper}>
<button></button>
<img src={images[0]} alt="" />
<button></button>
</div>
);
};
export default ImageSlider;
父组件:
...
let sliderImages: string[] = [
"../../assets/Dotrice/dotrice-background.png",
"../../assets/Dotrice/dotrice1.png",
"../../assets/Dotrice/dotrice2.png",
"../../assets/Dotrice/dotrice3.png",
"../../assets/Dotrice/dotrice4.png",
];
return (
<ImageSlider images={sliderImages} />
);
...
我是否必须在某处明确设置数组索引的类型?
谢谢,祝你有美好的一天,并保持安全:)