首页 > 解决方案 > 如何在反应中使用相同的按钮允许位置权限和撤销权限?

问题描述

嗨,我是编程新手。

我想实现以下目标,

单击按钮时,它应该显示一个本机浏览器弹出窗口,询问用户位置许可。接受许可应以绿色显示按钮。如果用户想要禁止位置共享,那么他使用相同的按钮来执行此操作。

到目前为止我尝试了什么?

下面是代码,

class location extends react.purecomponent {
    state = {
        active: false,
    };

    componentdidMount() {
        navigator.permissions.query({name:'geolocation'}).then((result) => 
        {
            if (result.state === 'granted') {
                this.setState({active: true});
            } else if (result.state === 'prompt') {
                this.setState({active: false});
            } else if (result.state === 'denied') {
                this.setState({active: false});
            }
        });
    }

    show_position = (position) => {
        return position.coords.latitude;
    };

    handle_my_location = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(this.show_position, 
            null);
        } else {
            console.log("unavailable");
        }
    };
    render = () => {
        return (
            <button type="button" className={'icon' + (this.state.active ? '   active': '')} onClick={this.handle_my_location}}>
                <Svg width="16"/>
            </button>
        );
    };
}

现在的问题是如何使用相同的按钮来撤销权限(拒绝位置共享),这意味着在 handle_my_location 方法中我如何检查用户是否想要撤销或允许位置共享。如果撤销,那么应该调用

navigator.permissions.revoke({name:'geolocation'});

更好地解释用例。考虑用户首次登录应用程序。单击按钮。它显示位置共享弹出窗口。用户允许位置共享。此按钮处于活动状态。现在,如果用户想要撤销权限(意味着不允许位置共享)单击相同的按钮,那么我如何在 handle_my_location 方法中撤销权限。

有人可以帮我解决这个问题。谢谢。

标签: javascriptreactjs

解决方案


您可以进行基于状态的检查。如果 state active 不是 true,你可以请求位置,但是如果 state active 是 true,则意味着你已经拥有位置,你可以撤销权限。你可以做这样的事情

handle_my_location = () => {
        if(!this.state.active) {

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(this.show_position, 
            null);
        } else {
            console.log("unavailable");
        }
       } else {
           navigator.permissions.revoke({name:'geolocation'});

        }
    };

推荐阅读