我正在尝试使用 Geolocation API 显示我的当前位置。我试图通过在方法中返回数据并在 render()
中的返回内调用该方法来实现这一点。问题是它没有显示任何内容。
我知道我可以返回 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>
);
}
}
关于javascript - 无法在 React 中返回带有地理位置坐标的 JSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52564217/