在我的一个 react 组件中,
import React, { Component } from 'react';
import './css/addItem.css';
class AddItem extends Component {
constructor(props) {
super(props);
}
showPosition(position) {
console.log("Latitude: ",position.coords.latitude+
" Longitude: ",position.coords.longitude);
}
getGeoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
render() {
return (
<div>
.....
.....
<button onClick={this.getGeoLocation}>Get GeoLocation</button>
</div>
);
}
}
export default AddItem;
我的它说无法读取未定义的属性“showPosition”
。
地理位置根本不起作用
。
作为 React 新手,我尝试过,
this.showPosition = this.showPosition.bind(this);
在构造函数中。
但这并没有帮助。
有人请解释一下我做错了什么以及如何解决它吗?
最佳答案
您的函数getGeoLocation
被另一个上下文调用。 React 不会自动绑定(bind)您的事件监听器或任何其他函数。因此,您会在 getGeoLocation
中收到 this === undefined
。要解决此问题,您可以在构造函数中使用 this.getGeoLocation = this.getGeoLocation.bind(this)
,或者仅使用带有箭头函数的类属性。例如:
import React, { Component } from 'react';
import './css/addItem.css';
class AddItem extends Component {
constructor(props) {
super(props);
}
showPosition(position) {
console.log("Latitude: ",position.coords.latitude+
" Longitude: ",position.coords.longitude);
}
// We use class property with arrow function to bind context:
getGeoLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
render() {
return (
<div>
.....
.....
<button onClick={this.getGeoLocation}>Get GeoLocation</button>
</div>
);
}
}
export default AddItem;
关于javascript - 无法读取未定义的属性 x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49317407/