这里是初学者。我有一个使用地理定位 API 获取纬度和经度的按钮。我在控制台上得到的位置很好,但在输入框中显示它们时遇到问题(以便我稍后可以发布位置信息)。以下是我的组件代码:
export class GetLocation extends Component{
constructor(){
super();
this.state = {
latitude: '',
longitude: ''
};
this.getMyLocation = this.getMyLocation.bind(this);
}
ComponentDidMount(){
this.getMyLocation();
}
getMyLocation = (e) => {
let location = null;
let latitude = null;
let longitude = null;
if (window.navigator && window.navigator.geolocation) {
location = window.navigator.geolocation
}
if (location){
location.getCurrentPosition(function (position) {
latitude = position.coords.latitude;
longitude= position.coords.longitude;
console.log(latitude);
console.log(longitude);
})
}
this.setState({latitude: latitude, longitude: longitude})
}
render(){
return(
<div>
<p>Your location is </p>
<Field name="latitude" component="input" onChange={this.getMyLocation}/>
<button type="button" onClick={this.getMyLocation}>Get Geolocation</button>
</div>
);
}
}
我正在使用 redux-form
并且此组件是向导表单的一部分(如果您想知道 Field
组件)
最佳答案
ComponentDidMount
应该是 componentDidMount
。我相信您必须为您的 Field
设置一个 value
属性,对吗?
此外,正如@bennygenel提到的,您不需要在构造函数中绑定(bind)getMyLocation
,因为您已经在使用箭头函数(我在我的示例中做了,请随意更改它)。为了能够访问 getCurrentPosition
回调中的 this.state
,您需要绑定(bind)
成功回调或使用箭头函数。
class App extends React.Component {
constructor() {
super()
this.state = {
latitude: '',
longitude: '',
}
this.getMyLocation = this.getMyLocation.bind(this)
}
componentDidMount() {
this.getMyLocation()
}
getMyLocation() {
const location = window.navigator && window.navigator.geolocation
if (location) {
location.getCurrentPosition((position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
})
}, (error) => {
this.setState({ latitude: 'err-latitude', longitude: 'err-longitude' })
})
}
}
render() {
const { latitude, longitude } = this.state
return (
<div>
<input type="text" value={latitude} />
<input type="text" value={longitude} />
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - ReactJS - 获取点击纬度并将其显示在输入中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46387375/