Android 如何在React Native MapView中调用方法?

Android 如何在React Native MapView中调用方法?,android,reactjs,react-native,Android,Reactjs,React Native,我想为文档中的MapView组件调用一个方法 我完全不知道怎么做 const Map = props => { const mapRef = useRef(); const random = () => { console.log(mapRef); console.log(mapRef.current.getCamera()); } return <MapView ref={mapRef} onClick={random()} style={styles.ma

我想为文档中的MapView组件调用一个方法

我完全不知道怎么做

const Map = props => {
const mapRef = useRef();
const random = () => {
    console.log(mapRef);
    console.log(mapRef.current.getCamera());
}

return <MapView ref={mapRef} onClick={random()} style={styles.mapStyle}  provider={PROVIDER_GOOGLE} region={props.region} />;
})


这是我根据我在网上找到的内容尝试的,但我不断发现未定义的对象不是一个计算“mapRef.current.getCamera”的对象。

这里发生的事情是,在渲染组件时调用随机函数,此时mapRef为空

另一件事是,正如我所知,React本机组件没有onClick方法,在移动开发中它被称为onPress

因此,您需要将onClick={random}更改为onPress={random}。看,我删除了括号并更改了方法的名称

看看这个例子

export default function App() {
  const mapRef = useRef(null);
  const [text, setText] = useState('');

  const handleMapPress = () => {
    const region = {
      latitude: 37.78825,
      longitude: -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421
    };
    mapRef.current.animateToRegion(region); // Here I'm using one of the map methods
  }
    return (
      <View style={styles.container}>
        <Text>{text}</Text>
        <MapView ref={mapRef} onPress={handleMapPress} style={styles.mapStyle} />
      </View>
    );
}

您可以看到它在这个

中工作,这里的情况是,在渲染组件时调用随机函数,此时mapRef为null

另一件事是,正如我所知,React本机组件没有onClick方法,在移动开发中它被称为onPress

因此,您需要将onClick={random}更改为onPress={random}。看,我删除了括号并更改了方法的名称

看看这个例子

export default function App() {
  const mapRef = useRef(null);
  const [text, setText] = useState('');

  const handleMapPress = () => {
    const region = {
      latitude: 37.78825,
      longitude: -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421
    };
    mapRef.current.animateToRegion(region); // Here I'm using one of the map methods
  }
    return (
      <View style={styles.container}>
        <Text>{text}</Text>
        <MapView ref={mapRef} onPress={handleMapPress} style={styles.mapStyle} />
      </View>
    );
}
你可以看到它在这里工作