简体   繁体   English

如何在本机反应中将函数从孩子传递给父母?

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

I'm new to react native so many things are still new to me.我是新来的反应原生所以很多东西对我来说仍然是新的。 I've been working with a map component and I have a created a custom button to send the user at his/hers current position.我一直在使用地图组件,并且创建了一个自定义按钮以将用户发送到他/她的当前位置。 When I call this function inside the map.js (child) everything works fine but when I try to pass this function to a button on mapScreen (parent) and I get undefined.当我在 map.js(子)中调用此函数时,一切正常,但是当我尝试将此函数传递给 mapScreen(父)上的按钮时,我得到了未定义。 If someone could help, how can I call successfully this function from child to parent.如果有人可以提供帮助,我怎样才能成功地从孩子到父母调用这个函数。

CHILD COMPONENT子组件

 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;

PARENT家长

 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;

You can't.你不能。 But you can pass the function to child component as prop and update parent state or etc like this simple example:但是您可以将函数作为道具传递给子组件并更新父状态等,例如这个简单的示例:

 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>

You can simply use optional chaining operator too: instead of nameRef.current.value && nameRef.current.value can write : nameRef.current?.value您也可以简单地使用可选链接运算符:而不是nameRef.current.value && nameRef.current.value可以写: nameRef.current?.value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM