簡體   English   中英

如何在本機反應中將函數從孩子傳遞給父母?

[英]How to pass a function from child to parent in react native?

我是新來的反應原生所以很多東西對我來說仍然是新的。 我一直在使用地圖組件,並且創建了一個自定義按鈕以將用戶發送到他/她的當前位置。 當我在 map.js(子)中調用此函數時,一切正常,但是當我嘗試將此函數傳遞給 mapScreen(父)上的按鈕時,我得到了未定義。 如果有人可以提供幫助,我怎樣才能成功地從孩子到父母調用這個函數。

子組件

 export const mapView = React.createRef();

const Map = ({ animateToMap, ...props }) => {

  const longitudeDelta = 0.022;
  const latitudeDelta = 0.021;

  const [mapRegion, setMapRegion] = useState({
    latitude: 41.328269,
    longitude: 19.817853,
  });

  const getRegionForType = (type) => {
    const regionData = {
      longitude: mapRegion.longitude,
      latitude: mapRegion.latitude,
    };
   
    if (type == 'map') {
      regionData.longitudeDelta = longitudeDelta;
      regionData.latitudeDelta = latitudeDelta;
    }
    return regionData;
  };

  const getMapRegion = () => getRegionForType('map');
  const getMarkerCoords = () => getRegionForType('marker');

  const setRegionForLocation = (location) => {
    let coords = location.coords;
    let longitude = coords.longitude;
    let latitude = coords.latitude;

    if (mapRegion.longitude === longitude && mapRegion.latitude === latitude) return;

    setMapRegion({ longitude, latitude, longitudeDelta, latitudeDelta });
  };

  const loadLocation = () => {
    Location.getForegroundPermissionsAsync() // later it should be changed to getBackgroundPermissionAsync()
      .then((response) => {
        if (response.status !== 'granted') throw 'Permission to access location was denied';

        return Location.getCurrentPositionAsync({});
      })
      .then((location) => {
        if (!location) throw 'Problem  retrieving location';

        setRegionForLocation(location);
      })
      .catch((reason) => {
        console.log('Load location is not working efficently', reason);
      });
  };

//This is the function I want to call in the parent
  animateToMap = () => {
    mapView.current.animateToRegion(
      {
        latitude: mapRegion.latitude,
        longitude: mapRegion.longitude,
        longitudeDelta: 0.022,
        latitudeDelta: 0.021,
      },
      1000,
      console.log('Sucessfull animation'),
    );
  };

  useEffect(() => {
    loadLocation();
  }, []);

  return (
    <View style={{ flex: 1 }}>
      {mapRegion ? (
        <MapView
          provider={PROVIDER_GOOGLE}
          ref={mapView}
          initialRegion={getMapRegion()}
          region={getMapRegion()}
          style={styles.map}
          mapType={props.mapType}
        >
          {mapRegion != null && (
            <Marker coordinate={getMarkerCoords()}>
              <Entypo name="location-pin" size={60} color="purple" />
            </Marker>
          )}
        </MapView>
      ) : (
        <ActivityIndicator />
      )}
    </View>
  );
};

export default Map;

家長

 const animateToMap= useRef();

  console.log('location: ', animateToMap); // Here I see that is undefined

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <MapLook>
        <Map mapType={changeMapView} animateToMap={animateToMap} />

          <LocationView>
            <LocationBtn>
              <MaterialIcons
                name="my-location"
                size={30}
                color="purple"
                style={{ alignSelf: 'center', marginTop: 14 }}
                onPress={animateToMap.current} //This doesn't work at all
              />

            </LocationBtn>
          </LocationView>
       
      </MapLook>
    </SafeAreaView>
  );
};

export default MapScreen;

你不能。 但是您可以將函數作為道具傳遞給子組件並更新父狀態等,例如這個簡單的示例:

 function Parent() { const [name,setName]=React.useState(); return <div> <Child onChangeName={v=>setName(v)}/> Name filling in child component is: {name} </div> } function Child({onChangeName}) { const nameRef=React.useRef(); return <div> <input type="text" ref={nameRef}/> <button onClick={()=>onChangeName(nameRef.current.value && nameRef.current.value)}>Set Name</button> </div> } ReactDOM.render(<Parent/>,document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

您也可以簡單地使用可選鏈接運算符:而不是nameRef.current.value && nameRef.current.value可以寫: nameRef.current?.value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM