reactjs - React cloneElement and component instance -
i have following higher order component trying wrap in container element supplied prop:
import react, { proptypes } 'react'; export default (component) => { return class extends react.component { static proptypes = { containerelement: proptypes.element } static defaultprops = { containerelement: <div /> }; componentdidmount() { console.log(this.el); } render() { const containerprops = { ref: (el) => this.el = el }; return react.cloneelement(containerelement, containerprops, component); }; } }
i wrap component this:
export default animationcomponent(reduxform({ form: 'newresultform', validate })(newresultform));
but when log element in componentdidmount
empty <div/>
.
why passed in component not child of newly created container element?
your method of writing higher order component little unorthodox. react developers typically don't have write functions accept components , return new class definition unless they're writing redux-form itself. perhaps instead of passing component
argument, see if passing in props.children
work you:
<animationcomponent>{newresultform}</animationcomponent>
i'd define animationcomponent following:
export default class animationcomponent extends react.component { static proptypes = { containerelement: react.proptypes.element }; static defaultprops = { containerelement: <div /> }; render () { // each child of component, // assign each ref , store on component this[`child${index}`] // e.g. this.child1, this.child2, ... // then, wrap each child in container passed in on props: return react.children.map(this.props.children, (child, index) => react.cloneelement( this.props.containerelement, {ref: ref => this[`child${index}`] = ref}, react.cloneelement(child) ) ); } }
instead of wrapping form component in animationcomponent, export connected form class:
export default reduxform({ form: 'newresultform', validate })(newresultform));
now instead of being stuck how animationcomponent configured in newresultform's file, can configure our liking end rendering form. in addition providing flexibility, information needed configure animationcomponent more pertinent gets rendered:
export default class myapp extends react.component { render() { return ( <animationcomponent containercomponent="span"> <newresultform /> </animationcomponent> ); } }
i hope helped!
Comments
Post a Comment