简体   繁体   English

如何获得对儿童dom元素的引用

[英]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. 我正在尝试实现绑定到子DOM元素上的事件的包装器标签,然后根据它们执行某些操作。

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? Wrapper ,如何访问子DOM元素?

You can do that with React ref , try to check here How do I access refs of a child component in the parent component 您可以使用React ref来做到这一点,尝试在此处进行检查如何在父组件中访问子组件的ref

And React document about ref: Refs and the DOM 和关于ref的React文档: Refs和DOM

You can use ref to access any DOM element. 您可以使用ref来访问任何DOM元素。 However, you'll need to wait until react writes its changes to DOM and then you can access it using useEffect hook. 但是,您需要等待,直到react将其更改写入DOM,然后您才能使用useEffect挂钩对其进行访问。 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>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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