警惕RN中TextInput控件中因key不固定造成的输入后失去焦点,丢失字符等问题

根本原因: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外。或者通过代码令其不重复渲染。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值