首页 > 解决方案 > 这是 React 组件的正确用法吗?

问题描述

我是 React 的新手。我想与您分享我的组件文件。该代码在语法上是正确的并且执行得很好。我只想知道,它在逻辑上是否正确以及对状态等概念的正确使用。

将 GeoLocation API 中的 lng 和 lat 坐标保存到 MapContainer 状态是否正确?

是否正确使用 ComponentDidMount() 函数。

我还有什么其他方法可以改进代码。

// Map.js
import React from 'react'
import 'bootstrap/dist/css/bootstrap.css';
import GoogleMapReact from 'google-map-react';


function Map(props) {
    const screenHeight = window.screen.height;
    return (
        <div style={{ height: screenHeight - 250 }}>
            <GoogleMapReact
                bootstrapURLKeys={{ key: "123mykey" }}
                center={props.center}
                defaultZoom={props.zoom}
            ></GoogleMapReact>
        </div>
    );
}

Map.defaultProps = {
    center: {
        lat: 59.95,
        lng: 30.33
    },
    zoom: 11
};

export default Map

// MapContainer.js
import React from 'react'
import 'bootstrap/dist/css/bootstrap.css';
import Map from './Map'

class MapContainer extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            center: {
                lat: 0, lng: 0
            }
        }

        this.getLocation = this.getLocation.bind(this);
        this.showPosition = this.showPosition.bind(this);
    }

    getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(this.showPosition);
        } else {
            console.log("Geolocation is not supported by this browser.");
        }
    }

    showPosition(position) {
        this.setState({
            center: {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            }
        });
    }

    componentDidMount() {
        this.getLocation();
    }

    render() {
        return (
            <div className="row">
                <div className="col-md-9">
                    <Map center={this.state.center} />
                </div>
                <div className="col-md-3 d-sm-none d-md-block d-none d-sm-block">
                    <h1>Menu</h1>
                </div>
            </div>
        );
    }
}

export default MapContainer

标签: reactjs

解决方案


在我看来很好。你只需要导入'bootstrap/dist/css/bootstrap.css';在您的主 index.js 文件中。


推荐阅读