如何使用react native和react-native-maps设置带有ref和动画的选定标记

问题描述 投票:0回答:1

我正在尝试使用 ref 为选定的标记设置动画。

到目前为止,如果我按下一个标记,其中一个会跳转,但不会跳转到所选的一个,但我似乎无法更改所选的哪个?理想情况下,我希望能够按下一个标记并选择它,当我按下按钮时,它会为所选标记设置动画。

我尝试将当前标记添加到状态,但它不起作用,并且我尝试在单击时设置引用,但出现错误说其只读?我也尝试过将markerRef传递给handlePress并尝试用.current代替它,但效果不好?

代码是:

import React, { useRef, useState } from 'react';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
import MapView, { Marker } from 'react-native-maps';
import * as Animatable from 'react-native-animatable';

const MapWithMarkerAnimation = () => {
  const markerRef = useRef(null);


  const handleAnimateButtonPress = () => {
    if (markerRef) {
      markerRef.current.bounce(800);
    }
  };

  return (
    <View style={styles.container}>
      <MapView style={styles.map} initialRegion={{ latitude: 52.4194975, longitude: -1.5101260 }} >
        <Marker coordinate={{ latitude: 52.4194975, longitude: -1.5101260 }} onPress={handleAnimateButtonPress}>
          <Animatable.View ref={markerRef} animation="zoomIn" duration={1000} easing="ease-out">
            <View style={styles.marker} />
          </Animatable.View>
        </Marker>
        <Marker coordinate={{ latitude: 52.514825, longitude: -1.5101260 }} onPress={handleAnimateButtonPress}>
          <Animatable.View ref={markerRef} animation="zoomIn" duration={1000} easing="ease-out">
            <View style={styles.marker} />
          </Animatable.View>
        </Marker>
      </MapView>
      <TouchableOpacity style={styles.button} onPress={handleAnimateButtonPress}>
        <Text style={styles.buttonText}>Animate Marker</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
  marker: {
    width: 20,
    height: 20,
    borderRadius: 10,
    backgroundColor: 'red',
  },
  button: {
    backgroundColor: 'blue',
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderRadius: 5,
    marginTop: 10,
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default MapWithMarkerAnimation;
react-native react-hooks google-maps-markers react-native-maps
1个回答
0
投票

我终于通过在主 App.js 中添加它来让它工作了

const [selectedMarker, setSelectedMarker] = useState(null);
  const markerRefs = useRef([]);

  const handleMarkerPress = (index) => {
    setSelectedMarker(index);
    markerRefs.current[index].rubberBand(); // Animating selected marker
  };

然后将普通视图更改为

<Animatable.View ref={(ref) => (markerRefs.current[index] = ref)}>

并且可以通过调用来启动动画

handleMarkerPress(0)
- 0 是数组中的位置。

希望这可以帮助其他遇到同样问题的人。

© www.soinside.com 2019 - 2024. All rights reserved.