首页 > 解决方案 > 如何从函数组件获取值到类组件(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
  1. 使用位置.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};
};

任何建议都非常感谢......提前致谢

标签: javascriptreactjs

解决方案


是的。使用回调作为道具。

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>
       </>
    )
}

推荐阅读