点击图标触发iconPress时自定义TextInput无法清空文本如何解决
问题解决:调用iconPress无法清空自定义TextInput内容
问题根因
你遇到的问题本质是自定义TextInput没有作为受控组件和父组件状态绑定:你在父组件给TextInputCode传递了value={searchString}属性,但自定义的TextInputCode组件既没有接收value参数,也没有把该值传递给内部的原生TextInput组件,导致输入框实际是不受searchString状态控制的非受控组件,修改searchString自然不会触发输入框内容更新。
修复步骤
修改TextInputCode组件,补充接收value参数并绑定到内部TextInput即可,修改后代码如下:
const TextInputCode = ({ iconType, placeholder, onChange, onFocus, textContentType, autoCapitalize, autoCompleteType, iconPress, onClear, value // 新增接收父组件传递的value参数 }) => { return ( <View style={styles.inputView}> <Icon name={iconType} onPress={iconPress} size={20} /> <TextInput style={{ flex: 1, paddingHorizontal: 12, }} value={value} // 新增将value绑定到原生TextInput placeholder={placeholder} textContentType={textContentType} autoCapitalize={autoCapitalize} autoCompleteType={autoCompleteType} autoCorrect={false} onChangeText={(e) => onChange(e)} onFocus={onFocus} onClear = {onClear} /> </View> ); };
修复后输入框会完全跟随父组件searchString的状态变化,调用setSearchString("")时就会自动清空输入内容,原有iconPress的逻辑无需调整。
内容的提问来源于stack exchange,提问作者karste
相关产品推荐
相关产品推荐

