在 React 中不能 return 带有地理位置坐标的 JSX
Can't return JSX with Geolocation coordinates in React
我正在尝试使用地理定位 API 显示我的当前位置。我正在尝试通过 return 方法中的数据并在 render()
中的 return 中调用该方法来做到这一点。问题是它没有显示任何内容。
我知道我可以 return JSX 因为,像这样的东西有效:
test = () => {
return (
<h1>Hello World</h1>
)
}
render(){
return(
<div>
{this.test()}
</div>
)
}
但是当我尝试这个时,页面上什么也没有呈现:
currentLocation = () => {
return navigator.geolocation.getCurrentPosition(position => {
return (
<div>
<h1>Current Position:</h1>
<p>Latitude: {position.coords.latitude}</p>
<p>Longitude: {position.coords.longitude}</p>
</div>
)
})
}
render(){
return(
<div>
{this.currentLocation()}
</div>
)
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
lat: null,
lng: null,
}
}
componentWillMount() {
navigator.geolocation.getCurrentPosition(position => {
this.setState({ lat: position.coords.latitude, lng: position.coords.longitude });
}, err => console.log(err)
);
}
render() {
return (
<div >
<h1>Current Position:</h1>
<p>Latitude: {this.state.lat}</p>
<p>Longitude: {this.state.lng}</p>
</div>
);
}
}
适合我。
getUserCurrentLocation = () => {
navigator.geolocation.getCurrentPosition(
position => {
this.setState(state => {
return {
...state,
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
},
err => console.log(err)
);
};
componentWillMount() {
// get user location
this.getUserCurrentLocation();
}
我正在尝试使用地理定位 API 显示我的当前位置。我正在尝试通过 return 方法中的数据并在 render()
中的 return 中调用该方法来做到这一点。问题是它没有显示任何内容。
我知道我可以 return JSX 因为,像这样的东西有效:
test = () => {
return (
<h1>Hello World</h1>
)
}
render(){
return(
<div>
{this.test()}
</div>
)
}
但是当我尝试这个时,页面上什么也没有呈现:
currentLocation = () => {
return navigator.geolocation.getCurrentPosition(position => {
return (
<div>
<h1>Current Position:</h1>
<p>Latitude: {position.coords.latitude}</p>
<p>Longitude: {position.coords.longitude}</p>
</div>
)
})
}
render(){
return(
<div>
{this.currentLocation()}
</div>
)
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
lat: null,
lng: null,
}
}
componentWillMount() {
navigator.geolocation.getCurrentPosition(position => {
this.setState({ lat: position.coords.latitude, lng: position.coords.longitude });
}, err => console.log(err)
);
}
render() {
return (
<div >
<h1>Current Position:</h1>
<p>Latitude: {this.state.lat}</p>
<p>Longitude: {this.state.lng}</p>
</div>
);
}
}
适合我。
getUserCurrentLocation = () => {
navigator.geolocation.getCurrentPosition(
position => {
this.setState(state => {
return {
...state,
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
},
err => console.log(err)
);
};
componentWillMount() {
// get user location
this.getUserCurrentLocation();
}