简体   繁体   中英

React Hooks : UseRef not recognizing Event

I'm using React Hooks.I am trying to trigger a onclick event using useRef.


    const component1: React.FC<Props> = props {
      const node =useRef<HTMLDivElement>(null);

      const ClickListener = UseCallback((e:any)=>{
        if(node.current.contains(e.target))
         console.log("Event Contained");
        else console.log("Event not Contained");
      },[]);

      return (
        <div ref={node} onClick={ClickListener}>
         <FormControl>
           <InputLabel>{text}</InputLabel>
           <Select> {contents} </Select>
         </FormControl>
        </div>
      );
    };

I have this Component1 called by componentX and componentY.

The above code is failing to recognise onclick event on a componentX's node when componentY's select menu is opened.

Only after closing ComponentY's select menu and clicking again on ComponentX currently recognises the event. Any Suggestions on why itsn't recognized.I am using Material UI's select.

You should pass node in the dependancy list to the useCallback method. Otherwise, the node which refers to null while defining the ClickListener is not updated.

Go through the docs - useCallback . useCallback avoids redefining the function every time the component function is called. So any global variables inside the function definition has to be listed in dependancies array, so that react will redefine the function when ever the dependancies change.

 const ClickListener =UseCallback((e:any)=>{
    if(node.current.contains(e.target))
    console.log("Event Contained");
    else console.log("Event not Contained");
    },[node]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM