我是React native的新手,我正在尝试将数据(即用户当前位置)从子组件传递到父组件。
父母亲
const MapScreen = ({ navigation }) => {
const [changeMapView, setChangeMapView] = useState('standard');
const [buttonColor, setButtonColor] = useState('#ffffff');
const [iconColor, setIconColor] = useState('purple');
let currentPosition; // varibale that I have declared
console.log('current position in mapscreen.js', currentPosition)
return (
<SafeAreaView style={{ flex: 1 }}>
<MapLook>
<Map mapType={changeMapView} currentPosition={currentPosition} />
</MapLook>
<ButtonView>
<SatelitViewPanel
changeMapView={changeMapView}
setChangeMapView={setChangeMapView}
/>
<LocationViewPanel
currentPosition={currentPosition}
/>
</ButtonView>
</SafeAreaView>
);
};
export default MapScreen;
小孩
const Map = (props, currentPosition) => {
const [mapRegion, setMapRegion] = useState({
longitude: 12.5683,
latitude: 55.6761
});
const getRegionForType = (type) => {
const regionData = {
longitude: mapRegion.longitude,
latitude: mapRegion.latitude
};
return regionData;
}
const getMapRegion = () => getRegionForType('map');
currentPosition = getMapRegion()
console.log(currentPosition)
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});
}
return (
<View style={{ flex: 1 }}>
<MapView
provider={PROVIDER_GOOGLE}
style={styles.map}
mapType={props.mapType}
>
{mapRegion != null && (
<Marker coordinate={getMarkerCoords()}>
<Image source={require('../../assets/marker.png')} style={{ height: 90, width: 90 }} />
</Marker>
)}
</MapView>
</View>
);
};
export default Map;
当我
console.log(currentPostion)
在父组件中,它输出
undefined
.
我试着用hook state来做,但结果表明
setState
不是函数
如何将数据从子级传递到父级?