根本原因:react/react native 采用diff算法,若重新渲染时dom的key不同则会生成新dom,造成字符丢失,失去焦点等问题。
例如:
<SafeAreaView style={tw.style('bg-white', { flex: 1 })}>
<FlatList
contentContainerStyle={tw.style('p-5 mb-5')}
data={location}
keyExtractor={(item, index) => `${item.id}-${index}`}
renderItem={renderItem}
ListHeaderComponent={() => {
return (
<React.Fragment key={'haha'}>
<View
style={{
paddingVertical: 3,
borderBottomWidth: 1,
borderColor: 'rgba(105,105,105,1)',
marginBottom: 5,
}}
>
<TextInput
style={{
paddingLeft: 5,
fontSize: 20,
fontFamily: 'InterRegular',
color: 'rgba(105,105,105,1)',
}}
placeholder="place input your destination"
onChangeText={searchDestination}
/>
</View>
</React.Fragment>
);
}}
ListFooterComponent={() => {
return <View></View>;
}}
/>
</SafeAreaView>
本例中,TextInput控件虽然没有写在内容区而是写在了listHeader区,但是每次刷新仍然会出问题。
解决方法应该是将TextInput写到FlatList外。或者通过代码令其不重复渲染。