어떻게 React Native에서 구글 자동 완성 폼을 만듭니까
reactnative에는 이미 google-autocomplete의 놀라운 소프트웨어 패키지가 있지만, 더욱 맞춤형 인터페이스를 구축하려면 이 안내서를 따라 어떻게 실현하는지 보십시오.
다음은 본문 끝에 작성할 내용입니다.

나는 너에게 구글이 다음과 같은 방면의 자동 완성 데이터를 얻기 위한 API를 가지고 있다는 것을 알려주어서 매우 기쁘다.
The Place Autocomplete service is a web service that returns place predictions in response to an HTTP request. The service can be used to provide autocomplete functionality for text-based geographic searches, by returning places such as businesses, addresses and points of interest as a user types.
위치 자동 완성 API는 일반적으로 다음과 같은 형식을 사용합니다.
https://maps.googleapis.com/maps/api/place/autocomplete/json?key=API_KEY&input=SEARCH_KEYWORD
.이 API를 사용하려면 API 키가 필요합니다.너는 하나 사러 갈 수 있다here.구글플레이스 APIdocumentation를 통해 더 많은 정보를 얻을 수 있습니다.
그래서 저희가 할 건 4단계로 간소화할 수 있어요.

준비 다 됐어요?😄
새 React 네이티브 프로젝트 만들기🔥
react-native init autocompleteExample
항목으로 이동하여 실행
cd autocompleteExample
react-native run-ios
or
react-native run-android
1단계: 입력 양식 만들기
import React, {Component} from 'react';
import {View,TextInput,StyleSheet,SafeAreaView} from 'react-native';
export default class App extends Component {
render() {
return (
<SafeAreaView style={styles.container}>
<TextInput
placeholder="Search for an address"
placeholderTextColor="#000"
style={styles.searchBox}
onChangeText={(text) => this.searchLocation(text)}
value={this.state.searchKeyword}
/>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
searchBox: {
width: 340,
height: 50,
fontSize: 18,
borderRadius: 8,
borderColor: '#aaa',
color: '#000',
backgroundColor: '#fff',
borderWidth: 1.5,
paddingLeft: 15,
},
container: {
flex: 1,
backgroundColor: 'lightblue',
alignItems: 'center',
},
});
저희 앱은 지금 이렇게 해야 돼요.
2단계: Google places에서 키워드 검색
이제 사용자가 내용을 입력할 때마다 예측을 검색할 수 있도록 코드를 작성합시다.
검색 함수를
onChangeText
의 TextInput
속성에 연결하기 때문에 사용자가 내용을 입력할 때 searchLocation
함수를 실행합니다.이 함수에서 우리는 구글의 위치로 자동으로 API를 완성하여 사용자가 입력한 모든 키워드를 검색하고 일련의 예측을 얻을 것이다.
요청이 성공하면 함수를 실행합니다.
this.setState({
searchResults: response.data.predictions,
isShowingResults: true,
});
이 함수는 우리가 받은 데이터를 this.state.searchResults
로 전달하고 볼 값 this.state.isShowingResults
을 true
으로 설정하여 평면 목록 (곧 만들 것) 을 볼 수 있습니다. 왜냐하면 우리는 현재 데이터가 있기 때문입니다. searchLocation = async (text) => {
this.setState({searchKeyword: text});
axios
.request({
method: 'post',
url: `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${API_KEY}&input=${this.state.searchKeyword}`,
})
.then((response) => {
console.log(response.data);
this.setState({
searchResults: response.data.predictions,
isShowingResults: true,
});
})
.catch((e) => {
console.log(e.response);
});
};
이 API 요청을 실행하면 JSON(JavaScript 객체 표현) 형식으로 검색된 키워드의 처음 5개의 예측 목록을 포함하는 predictions
으로 표시된 그룹을 포함하는 응답이 반환됩니다.예를 들어, "Chi"라는 단어를 입력하면 다음과 같은 응답을 얻을 수 있습니다.
{
"predictions": [
{
"description": "Chicago, IL, USA",
"id": "53eeb015d61056c54245a909c79862532fc953ad",
"place_id": "ChIJ7cv00DwsDogRAMDACa2m4K8",
},
{
"description": "China",
"id": "10bfe2265f06933baf8c2f1e35bf3bf132d74377",
"place_id": "ChIJwULG5WSOUDERbzafNHyqHZU",
},
{
"description": "Chihuahua, Mexico",
"id": "26f4ee675aa61f33dd0ffc296b582baf2e08fa3e",
"place_id": "ChIJM0BIXZ1E6oYRex3dBqen8bc",
},
{
"description": "Chile",
"id": "c33bb522167791f4bf271ef9151c1d13a1dd1092",
"place_id": "ChIJL68lBEHFYpYRHbkCERPhBQU",
}
],
"status": "OK"
}
메모🍀: 나는 이 JSON 예시에서 응답 대상의 일부 부분을 생략하여 간단명료하게 유지하고 응답 대상에는 통상적으로 더 많은 정보가 있다.JSON 응답에는 다음과 같은 두 가지 루트 요소가 포함됩니다.
status
: 요청이 포함된 metadata.predictions
: 이 위치에 대한 정보를 포함하는 위치 그룹을 포함합니다.이러한 결과에 대한 상세한 정보는 구글Place Autocomplete Results을 참조하십시오.그 결과 특히 흥미를 느낀 것은
place_id
요소로 단독 조회를 통해 위치에 대한 보다 구체적인 details을 요청할 수 있다는 것이다.우리는 예측수조를state(또는redux)
this.state.searchResults
에 저장한 다음 예측 목록을 표시할 것입니다.보셨어요?😉.
단계 5: 자동 완성 데이터 표시
현재 우리는 상기 JSON의 예시와 같은 구조에서 자동 완성/예측 데이터를 얻었고 이를
this.state.searchResults
에 저장한다.자동 완성 데이터를 표시하기 위해서, 우리는 예측을 표시하기 위해
FlatList
아래에 놓을 것이다.
신속하게 완료:
{
this.state.isShowingResults && (
<FlatList
data={this.state.searchResults}
renderItem={({item, index}) => {
return (
<TouchableOpacity
style={styles.resultItem}
onPress={() => this.setState({searchKeyword: item.description})}>
<Text>{item.description}</Text>
</TouchableOpacity>
);
}}
keyExtractor={(item) => item.id}
style={styles.searchResultsContainer}
/>
);
}
이 부분에서 우리는 자바스크립트의 단락 평가 개념을 사용할 것이다.{
this.state.isShowingResults && (
<View>
//Our List
</View>
);
}
간단하게 말하자면, 이것은 첫 번째 매개 변수 (TextInput
가true일 때만 나머지 코드를 실행할 수 있다는 것을 의미한다. (목록이 포함된 보기를 표시합니다.)안녕하십니까🐣"
this.state.isShowingResults
값이 this.state.isShowingText
인 경우에만 렌더링됩니다.{
this.state.isShowingText &&
<Text> Hello there🐣 </Text>
}
이해해주셨으면 좋겠어요.😊, 만약 당신이 아니라면, 평론을 남겨 주세요.이 단락을 실행하는 것은 API 요청을 자동으로 완료할 때만 목록을 표시할 수 있도록 하기 위해서입니다.
그래서 우리 응용 프로그램은 지금 이렇게 해야 한다.

🎉 만세, 우리의 자동 완성 기능은 이제 일을 할 수 있습니다.
그러나 우리는 여전히 작은 문제가 하나 있다.만약
true
아래에 또 다른 구성 요소가 있다면?평면 목록은 아래의 분홍색 가상 보기를 어떻게 대체합니까?
이 문제를 해결하기 위해서 우리는 두 가지 일을 했다.
TextInput
과TextInput
를 감싸고 보기의 높이FlatList
의 값을 줍니다. 예를 들어 10을 누르면 그 아래의 모든 것의 앞에 표시됩니다....
<View style={styles.autocompleteContainer}>
<TextInput .../>
<FlatList ... />
</View>
//...styles
autocompleteContainer: {
zIndex: 10,
},
searchResultsContainer: {
width: 340,
height: 200,
backgroundColor: '#fff',
position: 'absolute',
top: 50,
},
이렇게🎉저희가 지금 검색이 잘 되고 있어요.
다음은 전체 코드입니다.
import React, {Component} from 'react';
import {
View,
Text,
FlatList,
TouchableOpacity,
TextInput,
StyleSheet,
SafeAreaView,
} from 'react-native';
import axios from 'axios';
const API_KEY = 'Your-API-Key';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
searchKeyword: '',
searchResults: [],
isShowingResults: false,
};
}
searchLocation = async (text) => {
this.setState({searchKeyword: text});
axios
.request({
method: 'post',
url: `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${API_KEY}&input=${this.state.searchKeyword}`,
})
.then((response) => {
console.log(response.data);
this.setState({
searchResults: response.data.predictions,
isShowingResults: true,
});
})
.catch((e) => {
console.log(e.response);
});
};
render() {
return (
<SafeAreaView style={styles.container}>
<View style={styles.autocompleteContainer}>
<TextInput
placeholder="Search for an address"
returnKeyType="search"
style={styles.searchBox}
placeholderTextColor="#000"
onChangeText={(text) => this.searchLocation(text)}
value={this.state.searchKeyword}
/>
{this.state.isShowingResults && (
<FlatList
data={this.state.searchResults}
renderItem={({item, index}) => {
return (
<TouchableOpacity
style={styles.resultItem}
onPress={() =>
this.setState({
searchKeyword: item.description,
isShowingResults: false,
})
}>
<Text>{item.description}</Text>
</TouchableOpacity>
);
}}
keyExtractor={(item) => item.id}
style={styles.searchResultsContainer}
/>
)}
</View>
<View style={styles.dummmy} />
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
autocompleteContainer: {
zIndex: 1,
},
searchResultsContainer: {
width: 340,
height: 200,
backgroundColor: '#fff',
position: 'absolute',
top: 50,
},
dummmy: {
width: 600,
height: 200,
backgroundColor: 'hotpink',
marginTop: 20,
},
resultItem: {
width: '100%',
justifyContent: 'center',
height: 40,
borderBottomColor: '#ccc',
borderBottomWidth: 1,
paddingLeft: 15,
},
searchBox: {
width: 340,
height: 50,
fontSize: 18,
borderRadius: 8,
borderColor: '#aaa',
color: '#000',
backgroundColor: '#fff',
borderWidth: 1.5,
paddingLeft: 15,
},
container: {
flex: 1,
backgroundColor: 'lightblue',
alignItems: 'center',
},
});
다음은 전체 환매 예시의 링크입니다https://github.com/mosoakinyemi/autocomplete-example
행운을 빕니다.
Reference
이 문제에 관하여(어떻게 React Native에서 구글 자동 완성 폼을 만듭니까), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mosoakinyemi/how-to-create-a-google-autocomplete-form-in-react-native-4ffb텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)