Created
September 22, 2018 06:23
-
-
Save EnixCoda/212b609a94a948568762bee161a0bef2 to your computer and use it in GitHub Desktop.
turn ref into render props
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class _ControllerX extends React.Component { | |
static propTypes = { | |
forwardRef: PropTypes.func | |
} | |
ref = r => this.r = r | |
someCallback() { | |
this.r.method() | |
} | |
render() { | |
return React.cloneElement(this.props.children, { | |
ref: r => { | |
this.props.forwardRef(r) | |
this.ref(r) | |
}, | |
}) | |
} | |
} | |
const ControllerX = React.forwardRef((props, ref) => <_ControllerX {...props} forwardRef={ref} />) | |
const usage1 = ( | |
<ControllerA> | |
<ControllerB> | |
<View /> | |
</ControllerB> | |
</ControllerA> | |
) | |
// -------------------------------- | |
function createRenderPropsForRef(BaseComponentClass) { | |
return class RenderProps extends React.Component { | |
render() { | |
const { children, ...otherProps } = this.props | |
return ( | |
<React.Fragment> | |
<BaseComponentClass {...otherProps} /> | |
{this.props.children(this)} | |
</React.Fragment> | |
) | |
} | |
} | |
} | |
class ControllerX extends React.Component { | |
someCallback() { | |
this.props.view.method() | |
} | |
render() { | |
// you can also render anything you want | |
return null | |
} | |
} | |
const ViewAsRenderProps = createRenderPropsForRef(ViewComponent) | |
const usage2 = ( | |
<ViewAsRenderProps> | |
{instanceOfView => ( | |
<React.Fragment> | |
<ControllerA view={instanceOfView} />, | |
<ControllerB view={instanceOfView} />, | |
</React.Fragment> | |
)} | |
</ViewAsRenderProps> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment