You need to enable JavaScript to run this app. React/TypeScript:无法通过数字索引访问props传递的字符串数组
优惠活动
大模型
产品
解决方案
定价
更多

React/TypeScript:无法通过数字索引访问props传递的字符串数组

报错根因

你碰到的TS7053类型报错,完全不需要通过显式设置数组索引类型来解决,问题出在子组件接收props的基础写法错了。
React函数组件的第一个入参,是合并了自定义类型定义、内置children字段的完整props集合(也就是报错提示里提到的PropsWithChildren类型),并不是单独的images字段。你现在的代码把整个props对象直接命名为了images,此时代码里写的images[0],本质是试图从这个props对象上取数字索引为0的属性——但props对象本身根本没有这个数字索引,自然就触发了类型报错。

两种常用修正写法

只要调整参数接收逻辑,正常从props里取出images数组字段就能解决问题:

  • 写法1:接收完整props对象,用点语法取字段
const ImageSlider: React.FC<ImageSliderProps> = (props) => {
    const [index, setIndex] = useState<number>(0);
    const slideRight = () => { };
    const slideLeft = () => { };

    return (
        <div className={styles.slider_wrapper}>
            <button></button>
            <img src={props.images[0]} alt="" />
            <button></button>
        </div>
    );
};
  • 写法2:更简洁的解构写法,直接从props参数中提取images字段
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>
    );
};

补充说明

你现有代码里的类型定义、父组件传值逻辑都是完全正确的:父组件传入的string[]类型数组,只要能正确从props中取到,本身就是标准可索引的字符串数组,天然支持用数字下标访问,根本不需要额外给数组索引入显式类型。

内容的提问来源于stack exchange,提问作者ninni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.19 23:54:04