javascript - 如何从函数组件获取值到类组件(App.js)?
问题描述
我有两个组件,父组件,即 App.js,它是类组件,子组件 Demo.js 是函数组件,我需要将经度和纬度值从 Demo.js 传递给 App.js。怎么做?
参考文件如下: 1. Demo.js
import React from 'react';
import PropTypes from 'prop-types';
import {usePosition} from '../components/usePosition';
const Demo = () => {
// I want to pass these values in App.js (class component)
const {latitude,longitude} = usePosition();
console.log('Lat', latitude);
console.log('Lon', longitude);
return (
<>
{!latitude && <><div>Trying to fetch location...</div><br/></>}
<code>
latitude: {latitude}<br/>
longitude: {longitude}<br/>
</code>
</>
);
};
export default Demo
- 使用位置.js
import {useState, useEffect} from 'react';
const defaultSettings = {
enableHighAccuracy: false,
timeout: Infinity,
maximumAge: 0,
};
export const usePosition = (watch = false, settings = defaultSettings) => {
const [position, setPosition] = useState({});
const [error, setError] = useState(null);
const onChange = ({coords, timestamp}) => {
setPosition({
latitude: coords.latitude,
longitude: coords.longitude,
accuracy: coords.accuracy,
timestamp,
});
};
const onError = (error) => {
setError(error.message);
};
useEffect(() => {
const geo = navigator.geolocation;
if (!geo) {
setError('Geolocation is not supported');
return;
}
let watcher = null;
if (watch) {
watcher = geo.watchPosition(onChange, onError, settings);
} else {
geo.getCurrentPosition(onChange, onError, settings);
}
return () => watcher && geo.clearWatch(watcher);
}, [settings]);
return {...position, error};
};
任何建议都非常感谢......提前致谢
解决方案
是的。使用回调作为道具。
class App extends React.Component {
gotLatLng = (lat, lng) => {
console.log('Lat', lat);
console.log('Lng', lng);
}
render(){
return (
<Demo passlatLng={this.gotLatLng} />
)
}
}
cost Demo = (props) => {
const {latitude,longitude} = usePosition();
useEffect(() => {
if(latitude && longitude){
props.passLatLng(latitude, longitude);
}
}, [latitude, longitude])
return (
<>
{!latitude && <><div>Trying to fetch location...</div><br/></>}
<code>
latitude: {latitude}<br/>
longitude: {longitude}<br/>
</code>
</>
)
}
推荐阅读
- firebase - Flutter Firebase Cloud Firestore 如何使用子集合过滤带有 where() 查询的流
- python - 如何处理序列项 0 错误?
- php - 在PHP中求和mysql数组
- node.js - Browsersync 不再有效
- javascript - Angular routerlink 导航到简单页面而不是页面/页面
- python - 将错误值附加到另一个列表中的问题
- php - 更新 mysql 表,查询自动生成的表单中的值
- flutter - 我尝试用颤振连接我的数据库 Atlas MongoDB,但它不起作用
- java - 标记的标注不在谷歌地图的中心
- aiohttp - 在 Python 3.8.3 上尝试以下代码时,我看到“405:不允许的方法”