如何在react-native-autocomplete-dropdown输入框中自动添加连字符
实现方案
核心逻辑
你需要新增输入格式化函数处理连字符自动插入逻辑,同时修正原有代码中输入事件冲突的问题,完整实现如下:
首先定义格式化工具函数:
// 输入文本格式化函数,自动处理连字符插入 const formatCprText = (input) => { // 先过滤所有非数字字符,避免非法输入干扰 const pureNumberText = input.replace(/\D/g, ''); // 长度不足6位直接返回纯数字 if (pureNumberText.length <= 6) { return pureNumberText; } // 超过6位自动在前6位后插入连字符 return `${pureNumberText.slice(0,6)}-${pureNumberText.slice(6)}`; };
修改组件代码
你原有代码中onChangeText和textInputProps内部的onChangeText存在逻辑冲突,需要统一调整,修改后的完整组件代码如下:
<AutocompleteDropdown ref={searchRef} onFocus={() => { setactiveCpr(true); }} clearOnFocus={false} controller={controller => { dropdownController.current = controller; }} dataSet={suggestionsList} onChangeText={text => { // 先格式化输入文本 const formattedText = formatCprText(text); // 如果调用接口需要传纯数字,可提取 const pureNum = text.replace(/\D/g,'') 传给接口 getSuggestions(formattedText); onChangeTextHandler(formattedText); }} onSelectItem={item => { item && setSelectedItem(item.id); item && fullLookUp(item.id); item && journalHistory(item.id); item && Laboratoriesvar(item.id); setSuggestionsList(null); }} onSubmit={() => { setactiveCpr(false); }} onClear={() => { setactiveCpr(false); setSelectedItem(null); }} loading={loading} useFilter={false} textInputProps={{ editable: !selectedItem, // 选中时显示选中项ID,未选中显示格式化后的输入内容 value: selectedItem || formatCprText(searchRef.current?.searchText || ''), style: { backgroundColor: theme.inputBg, color: '#000', paddingLeft: 13, fontSize: 14, }, }} rightButtonsContainerStyle={{ borderRadius: 25, right: 8, height: 30, top: 5, alignSelfs: 'center', backgroundColor: 'transparent', }} inputContainerStyle={{ backgroundColor: 'transparent', }} suggestionsListContainerStyle={{ backgroundColor: 'white', zIndex: 300, }} renderItem={(item, text) => ( <Text style={{color: '#000', padding: 15}}> {`${item.id} ${item.title}`} </Text> )} inputHeight={40} showChevron={false} />
适配说明
- 如果你调用后端接口需要传入不带连字符的纯数字,只需要在调用
getSuggestions等接口方法时,传入过滤后的纯数字字符串即可:text.replace(/\D/g, '') - 代码自动处理了删除场景:当用户删除到第6位时,连字符会自动消失,不会出现删不动的异常情况
- 自动过滤所有非数字输入,避免用户输入字母、符号等非法内容
内容的提问来源于stack exchange,提问作者Asish Prajapati
相关产品推荐
相关产品推荐

