React Native运行报错ReferenceError: FlatListItemSeparator未定义如何解决?
错误原因
- 第一:你定义
FlatListItemSeparator、FlatListHeader两个组件时没有加const关键字,属于未声明变量直接赋值,React项目默认启用的严格模式下会直接判定变量未定义。 - 第二:
HomeScreen是函数组件,不存在类组件的this实例指向,你用this.FlatListHeader、this.FlatListItemSeparator调用时,this上根本不存在这两个属性,自然找不到定义。
解决方法
- 给两个组件的定义加上
const关键字,修改后代码如下:
const FlatListItemSeparator = () => { return ( <View style={{ height: 1, width: "100%", backgroundColor: "#000", }} /> ); } const FlatListHeader = () => { return ( <View elevation={1} style={{ height: 100, width: "97%", margin: 5, backgroundColor: "#fff", borderWidth: 2.9, borderColor: "black", alignSelf: "center", shadowColor: "#000", shadowOffset: { width: 0, height: 16, }, shadowOpacity: 1, shadowRadius: 7.49 }} > <Text style={{ textShadowColor: 'black', textShadowOffset: { width: 1, height: 3 }, textShadowRadius: 10, fontSize: 40, fontWeight: '800', flex: 1, alignSelf: "center", paddingTop: 30 }} >Latest articles</Text> </View> ); }
- 修改
HomeScreen中FlatList组件的属性,去掉this.前缀,直接引用变量即可:
const HomeScreen = (props) => { console.log("articles: ", props.articles); return ( <View> <FlatList data={ props.articles } ListHeaderComponent = { FlatListHeader } ItemSeparatorComponent = { FlatListItemSeparator} keyExtractor={(item, index) => index.toString()} renderItem={({item}) => <ArticleItem article = { item } />} /> </View> ); }
补充说明
你和教程代码一致还报错,大概率是教程用的是旧版类组件写法,类组件中方法会挂载在this上,且旧项目可能未开启严格模式,隐式声明的全局变量不会触发报错。你当前项目用的是函数组件+严格模式的标准写法,所以会触发报错,不需要导入这两个组件,它们本身就是你在当前文件定义的。
内容的提问来源于stack exchange,提问作者nimramubashir
相关产品推荐
相关产品推荐

