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

React Native对象与构造函数实操求助:需可运行示例

Practical Map Marker Implementation with Objects & Constructors (React)

First, let's fix the core issues in your original code:

  • You tried using a plain object (mapMarkers) as a constructor with new—that won't work. Constructors need to be functions or classes.
  • Your renderMarker method wasn't returning anything or properly managing marker instances.

Here's a fully runnable React example that defines map markers using a constructor class, manages them in a component, and renders them:

import React, { Component } from 'react';

// Step 1: Define a constructor class for MapMarker
class MapMarker {
  constructor(key, contactName, location) {
    this.key = key;
    this.contactName = contactName;
    this.location = location; // Should be an object like { lat: 40.7128, lng: -74.0060 }
  }

  // Optional: Add a method to get marker info as a string
  getMarkerInfo() {
    return `${this.contactName} is at (${this.location.lat}, ${this.location.lng})`;
  }
}

// Step 2: React Component to manage and render markers
class Map extends Component {
  constructor(props) {
    super(props);
    // Initialize state with sample markers
    this.state = {
      markers: [
        new MapMarker(1, 'Alice Smith', { lat: 40.7128, lng: -74.0060 }),
        new MapMarker(2, 'Bob Johnson', { lat: 34.0522, lng: -118.2437 })
      ]
    };
  }

  // Method to render individual markers (mock for demonstration)
  renderMarker = (marker) => {
    return (
      <div key={marker.key} className="marker-card">
        <h3>{marker.contactName}</h3>
        <p>Location: Lat {marker.location.lat}, Lng {marker.location.lng}</p>
        <p>{marker.getMarkerInfo()}</p>
      </div>
    );
  };

  // Method to add a new marker (for interactivity)
  addNewMarker = () => {
    const newKey = this.state.markers.length + 1;
    const newMarker = new MapMarker(
      newKey,
      `New Contact ${newKey}`,
      { lat: Math.random() * 90 - 45, lng: Math.random() * 180 - 90 } // Random coordinates
    );
    this.setState(prevState => ({
      markers: [...prevState.markers, newMarker]
    }));
  };

  render() {
    return (
      <div className="map-container">
        <h2>Map Markers</h2>
        <button onClick={this.addNewMarker}>Add Random Marker</button>
        <div className="markers-list">
          {this.state.markers.map(this.renderMarker)}
        </div>
      </div>
    );
  }
}

export default Map;

Key Fixes & Explanations:

  • MapMarker Class: This is your constructor—using new MapMarker(...) creates instances with consistent properties and methods.
  • Component State: We store markers in state so React can re-render when markers are added/removed.
  • Rendering: The renderMarker function takes a marker instance and returns JSX to display it (replace this with actual map library components like Leaflet's <Marker> if using a real map).
  • Interactivity: The addNewMarker method demonstrates creating new marker instances and updating state.

To Run This:

  1. Make sure you have a React project set up (use create-react-app if you don't).
  2. Replace the contents of src/App.js with this code.
  3. Add some basic CSS in src/App.css to style the markers:
.marker-card {
  border: 1px solid #ddd;
  padding: 1rem;
  margin: 1rem 0;
  border-radius: 4px;
}
.map-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 0 1rem;
}
button {
  padding: 0.5rem 1rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

This example is self-contained and will run in any React environment. If you're using a specific map library (like Google Maps or Leaflet), you can swap out the mock renderMarker JSX with the library's marker component, passing the location prop to it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:41:21