有没有办法让反应组件中的道具与它一起操作并发送到渲染。
例如:
import React, {Component} from 'react';
export default class MapBox extends Component {
componentDidMount() {
L.mapbox.accessToken = 'here my token';
var map = L.mapbox.map('map', 'some info', { zoomControl: false }).setView([48, 17], 5);
new L.Control.Zoom({ position: 'topright' }).addTo(map);
var path = [];
this.props.data.map(function(item, i) {
var icon;
if (i === 0) {
icon = L.mapbox.marker.icon({
'marker-color': '#1087bf',
'marker-size': 'large',
'marker-symbol': 'airport',
});
} else {
icon = L.mapbox.marker.icon({
'marker-color': '#f86767',
'marker-size': 'large',
'marker-symbol': 'airport',
});
}
var coordinates = [];
var data = item.coordinates;
data.map(function(item) {
coordinates.push(parseFloat(item));
});
L.marker(coordinates, {
icon: icon,
}).addTo(map).bindPopup(item.flight.from.city);
path.push(coordinates);
});
path.push(path[0]);
var polyline_options = {
color: '#1087bf',
weight: 2,
opacity: 1
};
L.polyline(path, polyline_options).addTo(map);
}
render() {
return (
div id="map" className="map_result"
);
}
}
请不要查看渲染块html,因为我不知道如何用括号发布它。
答案 0 :(得分:0)
您可以this.props
方法访问render
。如果您想在每次组件渲染时计算path̀̀
,请在那里进行计算。如果您只想计算一次 - 似乎 - 然后将其分配给this.path
而不是局部变量,或使用this.setState({ path: path })
将其存储到组件的状态。
此外,当使用map
时,您希望从传递给它的函数中返回一个对象,并希望将其存储在结果数组中:
var path = this.props.data.map(function(item, i) {
// compute coordinates
return coordinates;
});
console.log(path); // [coordinates_for_data_item_1, coordinates_for_data_item_2, coordinates_for_data_item_3]
答案 1 :(得分:0)
您正在使用ES6,要获取道具对象,您必须定义构造函数才能访问它们:
import React, {Component} from 'react';
export default class MapBox extends Component {
// Add this block to your code
constructor(props) { // <<------ see them
super(props);
this.props = props;
}
componentDidMount() {
L.mapbox.accessToken = 'here my token';
var map = L.mapbox.map('map', 'some info', { zoomControl: false }).setView([48, 17], 5);
new L.Control.Zoom({ position: 'topright' }).addTo(map);
var path = [];
this.props.data.map(function(item, i) {
var icon;
if (i === 0) {
icon = L.mapbox.marker.icon({
'marker-color': '#1087bf',
'marker-size': 'large',
'marker-symbol': 'airport',
});
} else {
icon = L.mapbox.marker.icon({
'marker-color': '#f86767',
'marker-size': 'large',
'marker-symbol': 'airport',
});
}
var coordinates = [];
var data = item.coordinates;
data.map(function(item) {
coordinates.push(parseFloat(item));
});
L.marker(coordinates, {
icon: icon,
}).addTo(map).bindPopup(item.flight.from.city);
path.push(coordinates);
});
path.push(path[0]);
var polyline_options = {
color: '#1087bf',
weight: 2,
opacity: 1
};
L.polyline(path, polyline_options).addTo(map);
}
render() {
return (
div id="map" className="map_result"
);
}
}