let lon, lat;
let weather;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
console.log(typeof lat)
});
}
class Button extends React.Component{
state = {latt: lat}
render(){
return(
<div>
{this.state.latt}
<h1>ss</h1>
</div>
)}}
class Appp extends React.Component {
render(){
return(
<Button />
)}
}
ReactDOM.render(<Appp />, mountNode)
当我在console.log中变量时,我得到一个数字,但为什么我不能将它用作状态值。即使把它放在一个数组中也没什么区别。
答案 0 :(得分:0)
它应该是这样的:
let lat, lon, weather;
class Calendar extends React.Component {
constructor(props){
super(props);
this.state = {
lat: null,
lon: null
}
this.updateLatLon = this.updateLatLon.bind(this);
}
updateLatLon(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
this.setState(() => {
return {lat: position.coords.latitude, lon: position.coords.longitude}
});
});
}
}
componentWillMount(){
this.updateLatLon();
}
render(){
return (
<div>
{this.state.lat}
</div>
)
}
}
答案 1 :(得分:0)
您可以使用setState()
navigator.geolocation.getCurrentPosition(function(position) {
this.setState({
lat: position.coords.latitude,
lon: position.coords.longitude
});
console.log(typeof lat)
});