简体   繁体   中英

I want to access dom even in a modal with React-slick (useRef)

Currently, I'm using react-slick to implement it. I want to access the slider dom with useref (ref.cuurent), but the moment the modal opens, it becomes null. You can access it by sliding it. I think it's probably because I'm accessing it within a modal. How do I get a ref.cuurent the moment the modal opens?


export const index: React.FC = () => {
    const [isShowHowToModal, setIsHowToModal] = useState(true)

    return (
        <Box>
            <div>hello</div>
            {isShowHowToModal && <Modal setIsHowToModal={setIsHowToModal} />}
        </Box>
    )
}



import Slider from 'react-slick'

export const Modal = React.FC<Props>(setIsModal) => {
  
  const onClickCancel = () => {
    setIsModal(false)
  }

  const refs = useRef<Slider>(null)
  console.log(refs)

  const settings = {
    dots: false,
    infinite: false,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
  }

  return (
    <Slider ref={refs} {...settings}>
      <div>aaa</div>
      <div>bbb</div>
      <div>ccc</div>
    </Slider>
}

It would be helpful if you could answer with the function component.

Try to access the ref inside useEffect hook, right now you logging it on the first render before the Slider is rendered.

EDIT:

In your example you have multiple syntactic errors, they might or might not be the reason you have a problem. Anyway check out this sandbox , take a look at console, it successfully logs the refs .

Sidenote: If you exporting React.FC named index and using it like this <index> </index> it won't render the component, but instead will try to find and "index" dom element.

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