How to get the dom node of a child in a component without adding logic to its parent / child?

The following example WrapperCompshould access the dom node divson line 5 and line 8 without adding logic to PageCompor ItemComp. The only thing I could change into was the PageCompdiv tags. For instance. I might add to them ref, prop, data-attributeetc.

divsno need to create inside PageComp. WrapperCompthey will be allowed to create them too, but they must wrap each of its children (in this case, each ItemComp).

Example

class PageComp extends React.Component {
  render() {
    return (
    <WrapperComp>
      <div>
        <ItemComp/>
      </div>
      <div>
        <ItemComp/>
      </div>
    </WrapperComp>
    );
  }
}

class WrapperComp extends React.Component {
  render() {
    return (
      <div>
        <h1>A wrapper</h1>
        {this.props.children}
      </div>
    );
  }
}

class ItemComp extends React.Component {
  render() {
    return (
      <div>
        <h1>An item</h1>
      </div>
    );
  }
}

ReactDOM.render(
  <PageComp/>,
  document.getElementById('app')
);

Jsbin

What I have tried so far:

  • I already tried to put ref=on divs, but refwill only be available at PageCompnot in WrapperComp.
  • divs WrapperComp ref=, Refs Must

... ?

, , data-attribute div dom componentDidMount : document.querySelectorAll('[data-xxx]'). , , , .

node WrapperComp?

, . WrapperComp. , , . clientHeight.

+4
1

, , DOM, .., .

<PageComp>, <WrapperComp> , , , .

class PageComp extends React.Component {
  render() {
    return (
      <WrapperComp>
        <ItemComp/>
        <ItemComp/>
      </WrapperComp>
    );
  }
}

class WrapperComp extends React.Component {
  render() {
    const wrappedChldren = React.Children.map(this.props.children, function(child) {
      return (
        <div ref={function(div) {
            this.setState{clientHeight: div.clientHeight}
        }}>
          <h1>A wrapper</h1>
          { child }
        </div>
      ); 
    });
    return <div>{ wrappedChildren }</div>;
  }
}

<WrapperComp>, , .

+1

Source: https://habr.com/ru/post/1648920/


All Articles