React Native+TS开发FlatList出现No overload matches this call错误如何解决
问题根源
你遇到的报错本质是renderItemPlastic函数没有返回符合要求的React元素:
你使用了带大括号的箭头函数语法,但没有添加return语句返回JSX内容,函数默认返回void,和FlatList要求renderItem必须返回React元素/null的类型定义不匹配,触发了Typescript的类型校验错误。
修复方案
两种修改方式二选一即可:
- 给函数添加return语句,明确返回JSX内容:
const renderItemPlastic = ({item}: {item: arrayPlasticsData}) => { // 新增return关键字 return <PlasticItemComponent item={item} onSelected={handleSelected} /> };
- 使用箭头函数隐式返回语法,省略大括号和return:
// 去掉函数体的大括号,直接返回JSX const renderItemPlastic = ({item}: {item: arrayPlasticsData}) => <PlasticItemComponent item={item} onSelected={handleSelected} />
可选的类型优化建议
还有几个可以优化Typescript写法的点,避免后续出现同类问题:
- 你定义的
plasticsScreenComponentProps接口里多余声明了renderItem属性,该属性不是当前组件的入参,可以直接删除。 - 不要用
any标注navigation和route的类型,可以使用React Navigation官方提供的NavigationProp和RouteProp类型做标注,获得更完整的类型提示。 - 可以直接给FlatList指定泛型,不需要单独给renderItem的入参标注类型,写法更简洁:
<FlatList<arrayPlasticsData> data={plasticTypes} keyExtractor={item => item.id} renderItem={({item}) => <PlasticItemComponent item={item} onSelected={handleSelected} />} />
内容的提问来源于stack exchange,提问作者Joaquin Palacios
相关产品推荐
相关产品推荐

