React Override Components from other "module"

时间:2018-10-05 09:17:21

标签: reactjs

I want to create multiple applications based on the same codebase. All websites will be pretty much identical, but some of them might have some additional/different logic/templates.

Actually, we are using Java EE/JSF for our projects, but I want to migrate to another "fronted" framework. My goal is to replace the JSF with react Currently, we have 1 project, which is called product and for all customers, we have "projects", which can override the core "product"

For example: We have a dialog in the core codebase, which has 3 fields to fill. One customer needs one field more, but the rest is the same.

So I have 2 two questions:

1. How can I override the components used in the core module?

2. When inheriting a component, is it possible to only override part of the parent template?

Thanks

1 个答案:

答案 0 :(得分:0)

  

如何覆盖核心模块中使用的组件?

不能仅通过JavaScript覆盖模块。这可以在构建步骤中通过引入模块别名来解决,例如与Webpack。原始组件模块应该是替代组件模块的别名。

这可以视为临时措施,因为它对开发人员而言并不明显,需要其他配置,并且可能随着时间而变得复杂。

为了使用JavaScript覆盖特定组件,应将应用程序重构为以某种方式使用依赖项注入模式。可以通过上下文API或Redux存储为整个应用程序提供依赖项注入容器。例如。可以选择将上下文提供给应用程序,以覆盖那些有望被覆盖的组件:

const DepContext = React.createContext({});

const MyApp = props => (
  <DepContext.Provider value={{Foo: MyFoo}}>...</DepContext.Provider>
);

依赖于此组件的组件将被覆盖或原始组件:

import OriginalFoo from '../components/foo';

const Bar = props => (
  <DepContext.Consumer>
    {({ Foo = OriginalFoo }) => (
      <Foo/>
    )}
  </DepContext.Consumer>
);
  

继承组件时,是否可以仅覆盖父模板的一部分?

没有好的方法,继承的组件应该复制并粘贴布局:

class Foo extends Component {
  render() {
    return (
      <div>
        Some layout
        <div>Nested layout</div>
      </div>
    );
  }
}

这对于细粒度的组件来说应该不是问题,render可以用最少的努力重新组成:

class Foo extends Component {
  render() {
    return (
      <SomeFooLayout>
        <NestedFooLayout/>
      </SomeFooLayout>
    );
  }
}

class MyFoo extends Foo {
  render() {
    return (
      <SomeFooLayout>
        <NestedFooLayout/>
        <MoreNestedFooLayout/>
      </SomeFooLayout>
    );
  }
}
相关问题