pass ref to a class component with React.cloneElement and render prop

試著忘記壹切 提交于 2019-12-05 11:33:16

I had almost an identical issue.
i chose to use findDOMNode from react-dom, you can see the full solution in react-external-click.

Although the warning notes:

findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction.

findDOMNode only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling findDOMNode() in render() on a component that has yet to be created) an exception will be thrown.

findDOMNode cannot be used on functional components.

I think this is the better solution for this particular challenge.
It let's you be "transparent" to the consumer, while being able to target the component in the DOM.

Ok here it is, grabbing the ref:

componentDidMount() {
    this.ref = findDOMNode(this);
    // some logic ...
}

this is how i use a render function with no wrapper of my own:

render() {
        const { children, render } = this.props;
        const { clickedOutside } = this.state;
        const renderingFunc = render || children;

        if (typeof renderingFunc === 'function') {
            return renderingFunc(clickedOutside);
        } else {
            return null
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!