如何实时获取GooglePlacesAutocomplete组件中用户的输入文本?
解决Google Places Autocomplete实时获取输入内容的方案
方法一:利用组件自带的onChangeText回调
GooglePlacesAutocomplete组件本身提供了onChangeText属性,专门用于监听输入框的文本变化,这是最直接可靠的方式:
import { useState } from 'react'; // ... 其他导入 const SuggestionRow = ({ item }) => ( <View style={{}}> <View style={{}}></View> <Text style={{}}>{item.description}</Text> </View> ); const SCREEN_WIDTH = Dimensions.get("window").width; export default function MapSearch({ setLocation }) { let predefined = []; const [inputValue, setInputValue] = useState(''); const placesRef = useRef(); return ( <View style={{ width: SCREEN_WIDTH, paddingHorizontal: 5 }}> <GooglePlacesAutocomplete placeholder="Search" onPress={(data, details) => { setLocation(details); }} // 新增监听输入变化的回调 onChangeText={(text) => setInputValue(text)} minLength={4} fetchDetails styles={{ textInput: styles.textInput, }} query={{ key: "", language: "en", }} predefinedPlaces={predefined} suppressDefaultStyles ref={placesRef} renderRow={(item) => <SuggestionRow item={item} />} /> </View> ); }
每次用户输入时,inputValue会实时同步输入内容,你可以直接基于这个状态做后续逻辑处理。
方法二:通过textInputProps控制内部输入框
如果需要更精细的输入框控制(比如同时监听焦点变化),可以通过textInputProps把回调传递给组件内部的TextInput:
import { useState } from 'react'; // ... 其他导入 const SuggestionRow = ({ item }) => ( <View style={{}}> <View style={{}}></View> <Text style={{}}>{item.description}</Text> </View> ); const SCREEN_WIDTH = Dimensions.get("window").width; export default function MapSearch({ setLocation }) { let predefined = []; const [inputValue, setInputValue] = useState(''); const placesRef = useRef(); return ( <View style={{ width: SCREEN_WIDTH, paddingHorizontal: 5 }}> <GooglePlacesAutocomplete placeholder="Search" onPress={(data, details) => { setLocation(details); }} minLength={4} fetchDetails styles={{ textInput: styles.textInput, }} query={{ key: "", language: "en", }} predefinedPlaces={predefined} suppressDefaultStyles ref={placesRef} renderRow={(item) => <SuggestionRow item={item} />} // 传递TextInput的自定义属性 textInputProps={{ onChangeText: (text) => setInputValue(text), // 可额外添加onFocus、onBlur等回调 }} /> </View> ); }
之前方法无效的原因
useEffect未添加依赖项,会导致组件每次渲染都执行,但placesRef.current?.getAddressText()无法实时同步输入框的最新值,组件内部并未将输入内容同步到这个方法的返回值中。useCallback作为ref的用法错误:ref回调接收的node是组件实例本身,不是带有current属性的对象,所以node?.current?.length的判断逻辑完全不成立,自然不会触发状态更新。
内容的提问来源于stack exchange,提问作者Gigi101
相关产品推荐
相关产品推荐

