在render()
我的 RN 组件类中,我调用了加载轮播的功能组件 A。A 中的这个 Carousel 然后在其renderItem
prop中调用功能组件 B。B 包含一个 FlatList w ref 定义为<FlatList ref={ref => (this.list = ref)} />
。
所以Athis.list.scrollToIndex()
在A中定义的onTouch调用中成功访问。我需要做的是this.list.scrollToOffset()
在定义了FlatList和ref的B中调用 - 但是当我这样做时我得到一个错误TypeError: TypeError: null is not an object (evaluating '_this.list.scrollToOffset')
我已经尝试在类级别使用 React.createRef() 但这也不起作用。
这是代码:
//component B
renderList = () => {
if (scrollPosition>0) {
//this call to list fails
this.list.scrollToOffset({
offset: scrollPosition
})
}
return (
<FlatList
ref={ref => (this.list = ref)}
...
/>
)
}
//component A
renderCarousel = () => {
return (
<View style={{ flex: 1 }}>
<View>
<TouchableOpacity
onPress={() => {
this.list.scrollToIndex({ index: 0 }) //this call to list works
}}
>
</TouchableOpacity>
</View>
{
showList && (
<Carousel
renderItem={this.renderList}
/>
)
}
</View>
)
}
我猜我正处于那个奇怪而可怕的 jsthis
区域。有任何想法吗??蒂亚!