简体   繁体   中英

How to get Element using useRef in ReactJS

I want to add some event on a schedule card of tui.calendar . I tried to get the root element then querySelectorAll the schedule card's attribute.

The schedule card, calendarRef exists. the root element from getRootElement exists the div tag of the schedules card, but my element still empty.

What is wrong? My purpose is to get the schedule card element then add contextmenu for each. Thanks!

Update: I changed useLayoutEffect to useEffect then it's work. But only on Codesanbox not my project:DI don't know why?

Here is my code

Check this out. It looks like it works. I've just got an instance of a calendar with getInstance() and then got a reference to the DOM element via instance.getElement(sc.id,sc.calendarId) .

useEffect(() => {
    if (calendarRef && calendarRef.current) {
      const instance = calendarRef.current.getInstance();
      schedules.forEach((sc) => {
        /*
        const instance = calendarRef.current?.getRootElement();
        const element = instance.getElementsByClassName(
          "tui-full-calendar-time-schedule "
        );
        const elementArr = Array.from(element!);
        console.log(elementArr);
        */
        console.log(instance.getElement(sc.id,sc.calendarId));
      });
    }
  });

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