代码之家  ›  专栏  ›  技术社区  ›  TaoPaipai

如何在hoc中获取包裹组件的高度?

  •  1
  • TaoPaipai  · 技术社区  · 6 年前

    是否有任何方法可以获得封装组件的DOM高度?

    我试图添加一个引用,但控制台错误了我 Function components cannot be given refs.

    我设置了 forward ref 但情况似乎并非如此。

    export default function withInfiniteScroll(Component) {  
      return class extends React.Component {
        componentDidMount() {
          window.addEventListener('scroll', this.onScroll, true);
        }
        onScroll = () => {
          // here
          console.log(
            'window.innerHeight👉', window.innerHeight,
            '\ndocument.body.offsetHeight👉', document.body.offsetHeight,
          );
        }
        render() {
          return <Component {...this.props} />;
        }
      };
    }
    

    我想记录 Component 但是这些日志毫无意义,它们是HTML正文的高度,而不是 成分 s。

    window.innerHeight👉 767 
    document.body.offsetHeight👉 767 
    

    但当我在Chrome控制台中时:

    console.log(document.getElementsByClassName('home-container')[0].clientHeight)
    > 1484
    

    哪一个 'home-container' 是包装组件:

    withInfiniteScroll(HomeContainer);
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Estus Flask    6 年前

    包装的组件应使用 forwardRef :

    function withInfiniteScroll(Component) {  
      return class extends React.Component {
        ref = React.createRef();
    
        componentDidMount() {
          window.addEventListener('scroll', this.onScroll, true);
        }
    
        onScroll = () => {
          console.log(this.ref.current.clientHeight);
        }
    
        render() {
          return <Component ref={this.ref} {...this.props} />;
        }
      };
    }
    
    const Foo = React.forwardRef((props, ref) => (
      <div ref={ref}>Foo</div>
    ));
    
    const FooWithScroll = withInfiniteScroll(Foo);
    

    或包装组件应添加容器dom元素:

    function withInfiniteScroll(Component) {  
      return class extends React.Component {
        // ...same as above
    
        render() {
          return <div ref={this.ref}><Component {...this.props} /></div>
        }
      };
    }