繁体   English   中英

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;

完整的源代码在这里

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

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

那么,我上面采取的方法好吗? 如果没有,有什么问题,我应该怎么做?

Facebook 团队建议在编写 React 代码时“使用惯用的 JavaScript 概念”,并且由于没有对 ES6 类的 mixin 支持,因此应该只使用组合(因为您只是在使用惯用的 Javascript 函数)。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM