javascript - 无法读取未定义的属性 x

标签 javascript reactjs

在我的一个 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/

相关文章:

javascript - 如何使用 javascript 将 a 值从一个页面传递到另一个页面

javascript - 引用输入字段值 JQuery 更改日期

javascript - 如何在 react 中一项一项地渲染列表中的项目?

javascript - 在 React 中显示每个动态 div 的组件

javascript - Redux - 如何从商店获取数据并发布它

javascript - 导航栏后面的 ReactJS 组件

javascript - 选中复选框已禁用(Jquery)

javascript - 无法找出我的代码有什么问题,Javascript/html/css

javascript - 无法定位 Canvas 的子元素

javascript - 警告 : Each child in an array or iterator should have a unique "key" prop. 检查 `Units` 的渲染方法