【发布时间】:2020-04-06 14:32:05
【问题描述】:
我在 react native 中面临一个似乎长期存在的问题。
我正在使用带有 RN 版本 0.59 的 Expo SDK35。由于代码库很大,我还没有更新到 Expo SDK36 / RN 0.60,但如果这可以解决我的问题,我可以更新。
我有一个 Animated.View 组件,它有一个 FlatList 子组件,我无法使用 FlatList 参考中应该可用的静态方法(尤其是 scrollToIndex())。请参阅下一个示例代码:
class Example extends React.Component{
constructor(props){
super(props);
this.myRef = null;
}
componentDidUpdate = () => {
/*
somewhere in code outside this class, a re-render triggers
and passes new props to this class.
I do have props change detection, and some more other code,
but I have removed it in order to minimize the code example here
*/
// This call throws:
// TypeError: undefined is not a function (near '...this._scrollRef.scrollTo...')
this.myRef.scrollToIndex({
animated: true,
index: 1,
viewOffset: 0,
viewPosition: 0.5
});
// Other suggested solution from SO
// This also throws:
// TypeError: _this.myRef.getNode is not a function. (In '_this.myRef.getNode()', '_this.myRef.getNode' is undefined)
this.myRef.getNode().scrollToIndex({
animated: true,
index: 1,
viewOffset: 0,
viewPosition: 0.5
});
}
render = () => <Animated.View style={{ /* ... some animated props */ }}>
<FlatList ref={(flatListRef) => { this.myRef = flatListRef; }}
// more FlatList related props
/>
</Animated.View>
}
我已尝试改用Animated.FlatList,但仍会引发与上述代码示例相同的错误。
我还尝试在收到的flatListRef 参数上使用 react native 的 findNodeHandle() 实用函数,但它返回 null。
我发现过去在 Stack Overflow 上多次发布过相同的问题,大多数都没有答案,或者对我不起作用。这些帖子也有点旧(一年左右),这就是为什么我再次发布同一问题的原因。
有人设法找到解决此问题的解决方案/解决方法吗?
编辑:可能的解决方法
当我在玩代码时,我尝试使用 ScrollView 组件而不是 FlatList - scrollTo 方法有效!
更改仅在 FlatList - ScrollView 特定道具上(因此,对于 ScrollView,它将是子级而不是 data={[...]} 和 renderItem={()=>{ ... }} 等),以及 componentDidMount 中的 scrollToIndex 方法被 scrollTo 替换.
带有 ScrollView 的类的 render 方法现在看起来像这样:
render = () => <Animated.View style={{ /* ... some animated props */ }}>
<ScrollView ref={(flatListRef) => { this.myRef = flatListRef; }}>
{/*
this.renderItem is almost the same as the
renderItem method used on the FlatList
*/}
{ this.state.dataArray.map(this.renderItem) }
</ScrollView>
</Animated.View>
请注意,ScrollView 没有 scrollToIndex() 方法,因此您必须手动跟踪子位置,并且可能需要实现自己的 scrollToIndex 方法。
我不会将此作为我问题的答案,因为根本问题仍然存在。但作为一种解决方法,也许你可以接受它并收工......
【问题讨论】:
标签: react-native animation reference undefined react-native-flatlist