【问题标题】:reactjs base class for all components所有组件的 reactjs 基类
【发布时间】:2015-10-09 13:24:27
【问题描述】:

我想要一个基础组件,我的所有高阶组件都对其进行扩展。类似于

<BaseComponent>
   <App1>
      <... Other Components>
   </App1>
</BaseComponent>

其中 BaseComponent 包含诸如

之类的东西
class BaseComponent extends React.Component {
   render() {
      return (
        <Wrapper>
             {this.props.children}
             <ModalContainer>
             </ModalContainer>
        <Wrapper>);
    }
}

最终目标是能够在任何应用程序中通过让我们说“message = 'Error'”,并且模式对话框将显示“错误”,而无需将模式组件放入每个应用程序中。

这可能吗?还是我在独角兽的领域。我读过一些关于高阶构图的文章,但乍一看,这似乎不是我要找的。​​p>

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    通过高阶组件进行组件组合是一种执行子类化之类的方法,但使用组合而不是继承。例如:

    function wrapInBaseComponent(Component) {
      // Return a new component that renders `Component`
      // with all the same props, but also renders some
      // other stuff
      return (props) => {
        const { message, ...otherProps } = props;
        return (
          <Wrapper>
            <Component {...otherProps} />
            <ModalContainer message={message}>
            </ModalContainer>
          </Wrapper>
        );
      };
    }
    

    然后你会做这样的事情:

    class MyComponent extends React.Component {
      // ...
    }
    
    const WrappedComponent = wrapInBaseComponent(MyComponent);
    

    或者,如果您启用了 ES7 装饰器,则可以将其用作装饰器:

    @wrapInBaseComponent
    class MyComponent extends React.Component {
      // ...
    }
    

    这就是react-reduxreact-dnd 之类的工作方式;您不会继承 ReactReduxBaseComponent 或类似的东西,而是将您的组件组合在一个渲染它的高阶组件中,但会添加额外的功能。

    【讨论】:

    • 所以如果我想渲染 MyComponent,id do '' ?
    • @LazyProgrammer 在第一个示例中,是的。许多人只是导出打包版本,甚至根本不公开非打包版本,但访问它对于测试很有用。
    猜你喜欢
    • 2018-12-05
    • 2020-11-18
    • 2021-11-24
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2019-09-17
    • 2021-11-12
    相关资源
    最近更新 更多