React Native中ScrollView的maxHeight动画时组件闪烁问题
问题:展开多个待办事项列表项时屏幕闪烁
我实现了一个可通过点击按钮展开/收起的待办事项列表:点击EXPAND按钮时,Animated.ScrollView的高度会通过动画调整——展开时从0变为100,收起时从100变为0。但当同时展开两个列表项时,屏幕会出现闪烁现象,该问题在Android模拟器和物理安卓设备上表现一致。

单个待办事项元素代码(已简化,不含DONE按钮)
import React, { useState, useRef, memo } from 'react'; import { Animated, Text, View, Button, ScrollView } from 'react-native'; import longText from '../data/data'; const ListObject = (props) => { // 展开/收起功能 const expandValue = useRef(new Animated.Value(0)).current; const [expandState, setExpand] = useState(false); const expandAnimation = () => { Animated.timing(expandValue, {toValue: 100, duration: 1000, useNativeDriver: false}).start(); setExpand(true); } const collapseAnimation = () => { Animated.timing(expandValue, {toValue: 0, duration: 1000, useNativeDriver: false}).start(); setExpand(false); } return ( <View style={{ margin: props.margin }}> <View style={{ flexDirection: 'row', backgroundColor: 'grey', borderRadius: 10, }}> <Button title='EXPAND' style={{ flex: 1, backgroundColor: 'blue', }} onPress={ expandState ? collapseAnimation : expandAnimation } /> </View> <Animated.ScrollView style={{ flex: 1, paddingHorizontal: 40, backgroundColor: 'grey', borderRadius: 10, maxHeight: expandValue }}> <Text>{ props.text }</Text> </Animated.ScrollView> </View> ); } export default memo(ListObject);
App代码(遍历生成所有待办事项元素并分配key)
import React, { useRef, useState } from 'react'; import { Animated, StyleSheet, ScrollView, Text, View, SafeAreaView, Button } from 'react-native'; import longText from './src/data/data'; import ListObject from './src/components/list-object' const styles = StyleSheet.create({ safeContainer: { flex: 1.2 }, headerContainer: { flex: 0.2, flexDirection: 'column', justifyContent: 'center', backgroundColor: 'lightblue', }, headerFont: { fontSize: 50, textAlign: 'center', }, scrollContainer: { flex: 1 } }); const App = () => { const numbers = [1,2,3,4,5,6,7,8,9]; const listItems = numbers.map((number) => <ListObject key={number.toString()} margin={10} headerText='I am the header of the to-do element' text={longText} /> ) return ( <SafeAreaView style={ styles.safeContainer } > <View style={ styles.headerContainer }> <Text style={ [styles.headerFont] }>LIST MAKER</Text> </View> <ScrollView style={ styles.scrollContainer }> {listItems} </ScrollView> </SafeAreaView> ); }; export default App;
我原本期望不会出现闪烁现象,但该问题在我的物理安卓设备上也会出现。我已搜索过类似问题并参考其他库的实现方式。
内容的提问来源于stack exchange,提问作者Christel-is-creative
相关产品推荐
相关产品推荐

