React函数组件Ref传递失败报错,寻求解决方法
解决React函数组件Ref传递失败的问题
问题根源
你碰到的警告是因为函数组件默认不支持直接接收ref,React要求通过React.forwardRef()实现ref的穿透传递,让父组件的ref能指向子组件内部的原生组件(这里是FlatList)。
修复方案
只需修改Onboarding组件,用forwardRef包裹它,把外部传入的ref传递给内部的FlatList即可:
修改后的Onboarding组件代码:
import React, { forwardRef } from 'react'; // 导入forwardRef import { Dimensions, FlatList, Image, Text, View } from 'react-native'; const windowWidth = Dimensions.get('window').width; const windowHeight = Dimensions.get('window').height; // 用forwardRef包裹组件,参数为(props, ref) const Onboarding = forwardRef(({ list, updateCurrentState }, ref) => { return ( <FlatList data={list} horizontal ref={ref} // 将外部传入的ref绑定到FlatList pagingEnabled onMomentumScrollEnd={updateCurrentState} contentContainerStyle={{ height: windowHeight * 0.75 }} showsHorizontalScrollIndicator={false} renderItem={({ item, index }) => { return ( <View style={{ alignItems: 'center' }}> <Image source={item.image} style={{ height: '75%', width: windowWidth }} /> <Text style={{ color: 'white', fontSize: 22, fontWeight: 'bold', marginTop: 30, }}> {item.title} </Text> <Text style={{ color: 'white', fontSize: 13, marginTop: 5, maxWidth: '80%', textAlign: 'center', lineHeight: 23, }}> {item.subtitle} </Text> </View> ); }} /> ); }); export default Onboarding;
额外提醒
你的代码里存在拼写错误:currentSate应该是currentState(多处出现),虽然不影响ref功能,但建议修正避免后续逻辑出错。
内容的提问来源于stack exchange,提问作者namnt
相关产品推荐
相关产品推荐

