尝试一下在线预览此示例展示了如何将 React 与 ViewModels
一起使用来创建自定义微件体验。 具体来说,它演示了如何使用 ZoomViewModel 创建自定义缩放按钮。
1. 设置 React 为 AMD 模块
首先,你需要在你的 dojoConfig 中添加 React
和 ReactDOM
作为 AMD
模块。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
window.dojoConfig = {
async: true,
packages: [
{
name: "react",
location: "https://unpkg.com/react@16/umd/",
main: "react.production.min"
},
{
name: "react-dom",
location: "https://unpkg.com/react-dom@16/umd/",
main: "react-dom.production.min"
}
]
};
现在可以将它们作为普通的 AMD 模块使用。
2. 创建一个简单的地图和视图
创建一个简单的地图,并将其添加到 MapView 或 SceneView 。如果您不熟悉视图或如何创建基本地图,请参阅以下参考资料:
1
2
3
4
5
6
7
8
9
10
11
12
13
const map = new Map({
basemap: "topo-vector"
});
const view = new MapView({
container: "viewDiv",
map: map,
center: [-100.33, 25.69],
zoom: 10,
ui: {
components: ["attribution"] // empty the UI, except for attribution
}
});
3. 创建 React 组件
创建一个具有初始状态和预定义属性的 React 组件。 有关这方面的更多信息,请参阅 React 文档。 接下来,将 React 组件的操作绑定到 ZoomViewModel 的方法。 也可以将 React 组件的样式与 View 的属性绑定,以确定当前的最小/最大缩放级别。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Zoom extends React.Component {
state = {
vm: new ZoomViewModel(),
maxZoomed: false,
minZoomed: false
};
componentDidMount() {
this.props.view.when(this.onViewLoaded);
}
onViewLoaded = (view) => {
this.state.vm.view = view;
watchUtils.init(view, "zoom", this.onZoomChange);
};
onZoomChange = (value) => {
this.setState({
maxZoomed: value === view.constraints.maxZoom,
minZoomed: value === view.constraints.minZoom
});
};
zoomIn = () => {
if (!this.state.maxZoomed) {
this.state.vm.zoomIn();
}
};
zoomOut = () => {
if (!this.state.minZoomed) {
this.state.vm.zoomOut();
}
};
render() {
const maxstate = this.state.maxZoomed ? "button circle raised disable" : "button circle raised";
const minstate = this.state.minZoomed ? "button circle raised disable" : "button circle raised";
return (
<div className="zoom-btns">
<div className={maxstate} onClick={this.zoomIn}>
<div className="center">
<i className="material-icons">add</i>
</div>
</div>
<div className={minstate} onClick={this.zoomOut}>
<div className="center">
<i className="material-icons">remove</i>
</div>
</div>
</div>
);
}
}
4.渲染 React 组件
接下来,为 React 组件创建一个 DOM 元素,并将其添加到 UI 布局中。完成后,呈现 React 组件。
1
2
3
const node = document.createElement("div");
view.ui.add(node, "bottom-left");
ReactDOM.render(<Zoom view={view} />, node);