我尝试在Leaflet
元素中添加来自React
的脚本,并且因为它包含<script>code</script>
,它会引发错误:
var Carte = React.createClass({
render: function() {
var styl = {
height: 400,
width: 800,
position: 'relative',
margin: 'auto'
}
return (
<div id="lguit">
<div id="map" style={styl}></div>
<script>
document.querySelector("#lat").val = lat;
document.querySelector("#lon").val = lon;
map = L.map("map", {
center: [
lat,
lon
],
minZoom: 5,
zoom: 5
});
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
attribution: "OpenStreetMap"
}).addTo(map);
</script>
</div>
);
}
});
我收到此错误:
Uncaught Error: Parse Error: Line 26: Unexpected token :
at http://localhost:8000/static/js/main-react.jsx?v=c3affc6ee4977467587b88895c12cccc:26:undefined
center: [
^
编辑:试过这个:
<script dangerouslySetInnerHTML={{__html: 'document.querySelector("#lat").val=lat;document.querySelector("#lon").val=lon;map = L.map("map", {center: [lat,lon],minZoom: 5,zoom: 5});L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {attribution: "OpenStreetMap"}).addTo(map);'}} />
并且脚本dident执行,但是在DOM完成加载后会工作(如果我在控制台中单独执行它)
答案 0 :(得分:0)
似乎正确的方法是使用componentDidMount
var Carte = React.createClass({
render: function() {
var styl = {
height: 400,
width: 800,
position: 'relative',
margin: 'auto'
}
return (
<div id="lguit">
<div id="map" style={styl}></div>
</div>
);
},
componentDidMount: function() {
document.querySelector("#lat").val=lat;
document.querySelector("#lon").val=lon;
map = L.map("map", {center: [lat,lon],minZoom: 5,zoom: 5});
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {attribution: "OpenStreetMap"}).addTo(map)};
}
});