初学者在这里。我有一个使用地理位置API获取经度和纬度的按钮。我的控制台上的位置很好,但我无法在输入框中显示它们(以便稍后可以发布位置信息)。下面是我对组件代码:ReactJS - 点击获取纬度并在输入中显示
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
组件)
尝试通过'值= {this.state.latitude}'托到你的'Field'组件。 –