获取更高阶组件(HOC)中包装组件的DOM节点?

时间:2016-09-25 22:41:49

标签: javascript reactjs

在以下示例中,如何从MyComponent内的Enhance获取渲染div的DOM节点?

Enhance.js

import { Component } from "React";

export var Enhance = ComposedComponent => class extends Component {
  constructor() {
    this.state = { data: null };
  }
  componentDidMount() {
    this.setState({ data: 'Hello' });
  }
  render() {
    return <ComposedComponent {...this.props} data={this.state.data} />;
  }
};

MyComponent.js

import { Enhance } from "./Enhance";

class MyComponent {
  render() {
    if (!this.data) return <div>Waiting...</div>;
    return <div>{this.data}</div>;
  }
}

export default Enhance(MyComponent); // Enhanced component

3 个答案:

答案 0 :(得分:2)

由于您的HOC直接呈现子组件,因此HOC中findDOMNode返回的数据应该是子节点的DOM节点。

export var Enhance = ComposedComponent => class extends Component {
    componentDidMount() {
        // Logs the DOM node returned by the wrapped component
        console.log( ReactDOM.findDOMNode( this.refs.child ) );
    }
    render() {
        return <ComposedComponent {...this.props} ref="child" />;
    }
};

答案 1 :(得分:1)

高阶组件是包装组件本身……已增强。 获取包装组件的dom节点等效于获取hoc的dom节点。

export var Enhance = ComposedComponent => class extends Component {
    componentDidMount() {
        // Logs the DOM node returned by the wrapped component
        console.log( ReactDOM.findDOMNode( this ) );
    }
    render() {
        return <ComposedComponent {...this.props}  />;
    }
};

这样,我也可以使用forwardRef模式

export default WrappedComponent => {
  class EnhancedComponent extends React.Component {
    constructor(props) {
      super(props);
    }

    componentDidMount() {
      const domNode = ReactDOM.findDOMNode(this);
      console.log(domNode);
    }

    render() {
      const { forwardedRef, ...otherProps } = this.props;
      return <WrappedComponent ref={forwardedRef} {...otherProps} />;
    }
  }

  const forwardRef = (props, ref) => <EnhancedComponent {...props} forwardedRef={ref} />;
  return React.forwardRef(forwardRef);
};

答案 2 :(得分:0)

findDOMNode使用似乎不赞成(https://github.com/yannickcr/eslint-plugin-react/issues/678#issue-165177220)和ref字符串值,我认为这些值会被折旧。您仍然可以使用ref并将ComposedComponent打包在divref,以便您访问该节点。

<div ref={ (elem) => { this.elem = elem; } }>
    <ComposedComponent { ...this.props }  />
</div>

修改 由于您使用的是React Component类,因此您不需要包装器。包装器是否是功能组件。