我目前正在以以下方式继承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类的混合,因此应该只使用组合(因为您只是在使用惯用的Javascript函数)。
在这种情况下,您可以使用一个composeModal函数,该函数接受一个组件并将其包装在一个高阶容器组件中返回。这个更高阶的组件将包含您想要传递给所有子组件的任何逻辑,状态和道具。
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);