javascript - React ES6 component inheritance: working, but not recommended? -


i'm inheriting es6 react base component in following way:

model.js (base component):

class modelcomponent extends react.component {      render() {         // re-used rendering function (in our case, using react-three's reactthree.mesh)         ...     }  }  modelcomponent.proptypes = {     // re-used proptypes     ... };  export default modelcomponent; 

then have 2 extending components both this:

import modelcomponent './model';  class robotretrocomponent extends modelcomponent {      constructor(props) {          super(props);          this.displayname = 'retro robot';          // load model here , set geometry & material         ...      }  }  export default robotretrocomponent; 

(full source code here)

this appears work fine. both models showing , working expect.

however, have read in multiple places inheritance not correct approach react - instead should using composition. again, mixins not supported in react v0.13?

so, approach i'm taking above ok? if not, what's problem, , how should instead?

the facebook team recommends 'using idiomatic javascript concepts' when writing react code, , since there no mixin support es6 classes, 1 should use composition (since making use of idiomatic javascript functions).

in case, can have composemodal function takes component , returns wrapped in higher-order, container component. higher-order component contain whatever logic, state, , props want passed down of children.

export default function composemodal(component){     class modal extends react.component {         constructor(props){            super(props)            this.state = {/* inital state */}        }         render() {            // here can pass down whatever want 'inherited' child            return <component {...this.props} {..this.state}/>        }     }     modal.proptypes = {       // re-used proptypes       ...    };     return modal } 

then can use composition function so:

import composemodal './composemodal';  class robotretrocomponent extends react.component {      constructor(props) {         super(props);         this.displayname = 'retro robot';         // load model here , set geometry & material         ...     }      render(){         return /* jsx here */     } }  export default composemodal(robotretrocomponent); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -