javascript - 如何在反应中使用相同的按钮允许位置权限和撤销权限?
问题描述
嗨,我是编程新手。
我想实现以下目标,
单击按钮时,它应该显示一个本机浏览器弹出窗口,询问用户位置许可。接受许可应以绿色显示按钮。如果用户想要禁止位置共享,那么他使用相同的按钮来执行此操作。
到目前为止我尝试了什么?
下面是代码,
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 方法中撤销权限。
有人可以帮我解决这个问题。谢谢。
解决方案
您可以进行基于状态的检查。如果 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'});
}
};
推荐阅读
- jmeter - Dynamic Refid is appended to the URL but i can't find refid in the response
- python - 字典不起作用,我也收到“KeyError:0”错误消息,我不知道这是什么意思:/(顺便说一下python)
- firebase - Pyrebase 认证不返回成功案例
- jmeter - jmeter,如何一次性设置“思考时间”?
- assembly - 在x86中将两个数字相乘(通过重复加法)
- python - 使用 pandas 读取 excel 文件并将其打印以将其插入到 Rest-API 的 http GET 语句中
- java - 如何使用 Kotlin 识别 AWS Amplify 中的身份验证错误类型?
- angular - 反应形式的 NgbDatepicker:设置初始值
- c# - 正确瞄准坦克
- r - 大型数据集可视化