简体   繁体   中英

How to get reference to child dom element

I'm trying to implement wrapper tags that binds to events on child DOM element and then does something according to them.

I have following code:


const Wrapper: React.FC = (props) => {
    // How do I get access to child div DOM element here??
    someComponent.eventListenerOn(childDOMElement);

    return <>{props.children}</>;
};

const ChildStuff: React.FC = () => {
    return (
        <Wrapper>
            <div id="xyzzy"></div>
        </Wrapper>
    );
};

In Wrapper , how do I get access to child DOM element?

You can do that with React ref , try to check here How do I access refs of a child component in the parent component

And React document about ref: Refs and the DOM

You can use ref to access any DOM element. However, you'll need to wait until react writes its changes to DOM and then you can access it using useEffect hook. Here's how you do it using hooks:

const Wrapper = (props) => {
    const ref = React.useRef(null);

    React.useEffect(() => {
      if (ref.current) {
        // ref.current has the DOM element. Do what you want.
      }
    })

    return <div ref={ref}>{props.children}</div>;
};

const ChildStuff = () => {
  return (
    <Wrapper>
      <div id="xyzzy"></div>
    </Wrapper>
  );
};

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