这里是从组件中编写代码以获得天气应用程序的建议/自动完成。该应用程序只需要经度和纬度来加载天气 API。我只是不知道如何从这个组件获取数据(取自 NPM 库):
import React, { useRef } from "react";
import { StandaloneSearchBox, useJsApiLoader } from "@react-google-maps/api";
const libraries = ['places'];
const PlaceComponent = () => {
const inputRef = useRef();
const { isLoaded, loadError } = useJsApiLoader({
googleMapsApiKey: process.env.REACT_APP_API_GOOGLE_KEY,
libraries
});
const handlePlaceChanged = () => {
const [ place ] = inputRef.current.getPlaces();
if(place) {
console.log(place.formatted_address)
console.log(place.geometry.location.lat())
console.log(place.geometry.location.lng())
}
}
return (
isLoaded
&&
<StandaloneSearchBox
onLoad={ref => inputRef.current = ref}
onPlacesChanged={handlePlaceChanged}
>
<input
type="text"
className="form-control"
placeholder="Enter Location"
/>
</StandaloneSearchBox>
);
};
export default PlaceComponent;
尝试将它们放入底部的导出默认值中,将其更改为命名组件以及我能想到的所有其他内容。我是 React 新手,所以真的很挣扎
您不能只是尝试从组件中获取某些特定数据,因为组件的主要工作是显示 UI。
但是,您可以让父组件/Context API(或运行主逻辑的任何组件)通过传入函数来从子组件获取状态值,并将从子组件获得的值存储在
state
中
.
这是一个示例代码,其中重要部分有注释。
import React, { useRef } from 'react'
import { StandaloneSearchBox, useJsApiLoader } from '@react-google-maps/api'
const libraries = ['places']
const PlaceComponent = ({ setSomeStorage }) => {
const inputRef = useRef()
const { isLoaded, loadError } = useJsApiLoader({
googleMapsApiKey: process.env.REACT_APP_API_GOOGLE_KEY,
libraries,
})
const handlePlaceChanged = () => {
const [place] = inputRef.current.getPlaces()
if (place) {
// pass the value to parent component state
setSomeStorage({
address: place.formatted_address,
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
})
}
}
return (
isLoaded && (
<StandaloneSearchBox onLoad={(ref) => (inputRef.current = ref)} onPlacesChanged={handlePlaceChanged}>
<input type="text" className="form-control" placeholder="Enter Location" />
</StandaloneSearchBox>
)
)
}
export default PlaceComponent
和父组件
const SomeParentComopnent = () => {
const [someStorage, setSomeStorage] = useState()
return <PlaceComponent setSomeStorage={setSomeStorage} /> // Pass the `setState` as prop to children component
}
注意传递到
PlaceComponent
中的 props,以及如何将值存储到 SomeParentComopnent
中的父组件。