React ES6 component inheritance: working, but not recommended?

前端 未结 1 371
北恋
北恋 2020-12-23 22:18

I\'m currently inheriting an ES6 React base component in the following way:

model.js (base component):

class ModelComponent extends React.Component {         


        
相关标签:
1条回答
  • 2020-12-23 22:57

    The Facebook team recommends 'using idiomatic JavaScript concepts' when writing React code, and since there is no mixin support for ES6 classes, one should just use composition (since you are just making use of idiomatic Javascript functions).

    In this case, you can have a composeModal function that takes a component and returns it wrapped in a higher-order, container component. This higher-order component will contain whatever logic, state, and props you want passed down to all of its children.

    export default function composeModal(Component){
    
       class Modal extends React.Component {
    
           constructor(props){
               super(props)
               this.state = {/* inital state */}
           }
    
           render() {
               // here you can pass down whatever you want 'inherited' by the child
               return <Component {...this.props} {..this.state}/>
           }
    
       }
    
       Modal.propTypes = {
          // Re-used propTypes
          ...
       };
    
       return Modal
    }
    

    Then you can use the composition function like so:

    import composeModal from './composeModal';
    
    class RobotRetroComponent extends React.Component {
    
        constructor(props) {
            super(props);
            this.displayName = 'Retro Robot';
            // Load model here and set geometry & material
            ...
        }
    
        render(){
            return /* Your JSX here */
        }
    }
    
    export default composeModal(RobotRetroComponent);
    
    0 讨论(0)
提交回复
热议问题