React+TypeScript组件报错:数组类型不存在url/text属性的解决方法
问题分析与解决方案
报错原因
你定义的linkData是数组类型({ text: string; url: string }[]),但组件代码里直接尝试访问props.linkData.url——数组本身没有url/text属性,只有数组索引和内置方法,因此TypeScript抛出类型错误。
解决方案(二选一,根据组件实际需求选择)
方案1:组件仅渲染单个链接(对应type="link"场景)
修改Props类型,将linkData从数组改为单个对象:
interface Props { className?: string; type: "link" | "dropdown"; // 移除数组标识[],定义为单个链接对象 linkData: { text: string; url: string }; }
组件代码无需修改,此时调用组件时需传入单个对象而非数组:
<SecondaryItem type="link" linkData={{ text: "О Вконтакте", url: "./" }} />
方案2:组件实现下拉菜单(对应type="dropdown"场景)
保留linkData的数组类型,通过遍历数组渲染所有下拉选项,同时区分type分支处理:
import React from 'react'; import cn from 'classnames'; interface Props { className?: string; type: "link" | "dropdown"; linkData: { text: string; url: string }[]; } export const SecondaryItem: React.FC<Props> = (props: Props): JSX.Element => { // 处理单个链接场景 if (props.type === "link") { const firstLink = props.linkData[0]; if (!firstLink) return null; // 空数组时返回占位或null return ( <li className={cn("secondary-item", props.className)}> <a className="secondary-item__link" href={firstLink.url}> {firstLink.text} </a> </li> ); } // 处理下拉菜单场景 return ( <li className={cn("secondary-item secondary-item--dropdown", props.className)}> <button className="secondary-item__trigger">展开菜单</button> <ul className="secondary-item__dropdown-list"> {props.linkData.map((item, idx) => ( <li key={idx} className="secondary-item__dropdown-item"> <a href={item.url}>{item.text}</a> </li> ))} </ul> </li> ); };
此方案下,你最初传入数组的调用方式完全符合要求,TypeScript不会再报错。注意渲染列表时需添加key属性,优先使用item的唯一标识(如id),无唯一标识时可临时用索引idx。
内容的提问来源于stack exchange,提问作者Viktor
相关产品推荐
相关产品推荐

