触发 usePosition() 自定义钩子 onClick 元素

当我尝试在事件中触发usePosition钩子时,我遇到了一些麻烦onClick。


我想要实现的是延迟浏览器触发的地理定位权限提示,直到用户单击某个元素。


到目前为止,我尝试过的是以下代码的一系列变体,但没有成功:


const IndexPage = () => {

        const [geolocation, setGeolocation] = useState({});

        const [isGeolocationActive, triggerGeolocation] = useState(false);

        let currentPosition = usePosition();


        function handleGeolocation() {

            if (isGeolocationActive) {

                setGeolocation(currentPosition)

                console.log('geolocation', geolocation)

            } else triggerGeolocation(true);

        }


        return (

            <Layout>

                <Wrapper type={`list`} classNames={`wrapper pet__cards cards__list`}>

                    <Card>

                        <Image/>

                        <div onClick={() => handleGeolocation()}>Click me to share my location</div>

我试图设置一个useState钩子(最初设置为 false),usePosition如果设置为 true ,它应该控制和处理钩子,但是一旦我登陆页面,浏览器仍然要求地理定位许可。


编辑:我还尝试将usePosition钩子放在另一个组件中并将其称为onClick事件。但是,在这种情况下,我面临一些钩子规则错误,例如:


“无效的钩子调用。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一发生......”


MMTTMM
浏览 168回答 1
1回答

慕标琳琳

最后我usePosition在另一个组件中使用钩子解决了这个问题,如下所示:import React from "react";import {usePosition} from "use-position";const Geolocation = () => {&nbsp; &nbsp; let currentPosition = usePosition();&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{currentPosition.latitude}</p>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )};export default Geolocation;在我的主要组件中,我使用了一个useState钩子来控制渲染,如下所示:const IndexPage = () => {&nbsp; &nbsp; const [geolocation, setGeolocation] = useState('');&nbsp; &nbsp; function handleGeolocation() {&nbsp; &nbsp; &nbsp; &nbsp; setGeolocation(<Geolocation/>);&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Layout>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Card>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Image/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div onClick={() => handleGeolocation()}>Click me to share my location</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {geolocation}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript