You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将React Native地图路线类组件转为函数式组件

转换后的函数式组件代码
import React, { useState, useRef } from 'react';
import { Dimensions, StyleSheet } from 'react-native';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';

const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.771707;
const LONGITUDE = -122.4053769;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;

const GOOGLE_MAPS_APIKEY = '…';

const Example = () => {
  // 初始化坐标状态,与原类组件初始值一致
  const [coordinates, setCoordinates] = useState([
    {
      latitude: 37.3317876,
      longitude: -122.0054812,
    },
    {
      latitude: 37.771707,
      longitude: -122.4053769,
    },
  ]);

  // 获取MapView实例引用
  const mapView = useRef(null);

  // 地图点击添加坐标的处理函数
  const onMapPress = (e) => {
    setCoordinates(prevCoordinates => [
      ...prevCoordinates,
      e.nativeEvent.coordinate,
    ]);
  };

  return (
    <MapView
      initialRegion={{
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      }}
      style={StyleSheet.absoluteFill}
      ref={mapView}
      onPress={onMapPress}
    >
      {coordinates.map((coordinate, index) =>
        <MapView.Marker key={`coordinate_${index}`} coordinate={coordinate} />
      )}
      {(coordinates.length >= 2) && (
        <MapViewDirections
          origin={coordinates[0]}
          waypoints={coordinates.length > 2 ? coordinates.slice(1, -1) : undefined}
          destination={coordinates[coordinates.length - 1]}
          apikey={GOOGLE_MAPS_APIKEY}
          strokeWidth={3}
          strokeColor="hotpink"
          optimizeWaypoints={true}
          onStart={(params) => {
            console.log(`Started routing between "${params.origin}" and "${params.destination}"`);
          }}
          onReady={result => {
            console.log(`Distance: ${result.distance} km`)
            console.log(`Duration: ${result.duration} min.`)

            mapView.current.fitToCoordinates(result.coordinates, {
              edgePadding: {
                right: (width / 20),
                bottom: (height / 20),
                left: (width / 20),
                top: (height / 20),
              }
            });
          }}
          onError={(errorMessage) => {
            // console.log('GOT AN ERROR');
          }}
        />
      )}
    </MapView>
  );
};

export default Example;

关键转换要点

  • 状态替换:用useState钩子替代类组件的this.state,直接传入初始坐标数组完成状态初始化,更新状态时采用函数式写法确保基于最新状态值。
  • 实例引用:用useRef钩子创建mapView引用,替代类组件中通过ref赋值给实例变量的方式,访问MapView实例时使用mapView.current。
  • 事件处理:类组件的箭头函数方法转为函数组件内的普通箭头函数,逻辑与原代码完全一致。
  • 模板渲染:移除所有this.state和this.mapView的引用,直接使用函数组件内定义的变量。

内容的提问来源于stack exchange,提问作者Festus Akushie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:56:09