React ES6 组件继承:有效,但不推荐?

React ES6 component inheritance: working, but not recommended?

我目前正在通过以下方式继承 ES6 React 基础组件:

model.js(基本组件):

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;

然后我有两个扩展组件,它们基本上都是这样的:

import ModelComponent from './model';

class RobotRetroComponent extends ModelComponent {

    constructor(props) {

        super(props);

        this.displayName = 'Retro Robot';

        // Load model here and set geometry & material
        ...

    }

}

export default RobotRetroComponent;

(Full source code here)

这似乎工作正常。两种模型都按照我的预期出现并工作。

但是,我在多个地方读到继承不是 React 的正确方法——相反我应该使用组合。但话又说回来,React v0.13 不支持 Mixins?

那么,我上面的方法可以吗?如果不是,问题是什么,我应该怎么做?

Facebook 团队建议 'using idiomatic JavaScript concepts' 在编写 React 代码时,由于没有对 ES6 的 mixin 支持 类,应该只使用组合(因为你只是在使用惯用的 Javascript 函数)。

在这种情况下,您可以有一个 composeModal 函数,它接受一个组件,并且 returns 它包装在一个更高阶的容器组件中。这个高阶组件将包含您想要传递给它的所有子组件的任何逻辑、状态和道具。

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
}

然后就可以像这样使用组合函数了:

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);