reactjs - 这是 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
解决方案
在我看来很好。你只需要导入'bootstrap/dist/css/bootstrap.css';在您的主 index.js 文件中。
推荐阅读
- haskell - 如何在 Haskell 中解决这个问题?
- python-3.x - 将列表中的值分配给字典列表中的特定值
- asp.net - 将 User.Identity.Name 分配给变量保持为空
- mysql - 更改 100M 行 Amazon RDS 表以添加新列
- php - Wordpress如何删除父类别并仅保留带有帖子标题的子类别
- gnuradio - Gnu Radio Companion 3.8 WX GUI 替换
- python - 在python中将非统一文件读入单个数组
- javascript - 表单控制输入中的 React js useReducer 钩子
- flutter - Flutter 如何使用 cookie 在浏览器中打开 url
- mysql - 统计 SQL 中属于另一个元素的元素数量(每个品牌的产品数量)