在以下示例中,如何从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
最佳答案
由于您的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" />;
}
};