【问题标题】:Generics OR decomposition? what is the right approach for react泛型还是分解?什么是正确的反应方法
【发布时间】:2020-03-20 04:55:52
【问题描述】:

我有一个在 Angular 中使用 typescript 开发的应用程序,它有 20 多个屏幕,其中包含不同实体的列表视图,例如电影列表、演员列表、剧院列表等。我创建了一个 BaseListComponent<T extends Base> 角度和封装大多数常用功能,如查看、过滤、删除、搜索、分页等都在这个BaseListComponent中。我正在创造它的孩子,比如MoviesListComponent extends BaseListComponent<Movies>。这样,我需要在子类中添加最少的功能,以减少错误范围以及单元测试用例的工作量。

现在我正在将此应用程序转换为带有 typescript 的 React。我正在研究 React hooks 并了解到许多开发人员更喜欢基于函数的方法而不是基于类的组件。如何使用函数创建上述结构。据我了解,函数没有继承。所以我怀疑泛型在功能上是否可行。如果没有,我该如何使用 react 流行的分解方法来解决这个问题? 是否有在反应中使用泛型或分解的指南?

【问题讨论】:

标签: reactjs redux functional-programming react-hooks


【解决方案1】:

要做到“反应风格”,首先你必须制作一个组件BaseListComponent。然后把你列出的“查看、过滤、删除、搜索、分页等”功能放在这个里面。但是,当您希望某些函数在派生类时表现不同时,您可以在该函数中放置一个回调。

例如:

renderView = () => { // function of BaseListComponent
  const header = (
    <div>--I am Header--</div>
  );
  const footer = () => (
    <div>--------</div>
  );
  const letDerivedClassDecide = this.props.renderCenter();
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
        {header}
        {letDerivedClassDecide}
        {footer}
    </div>
  );
}

这个例子的意思是,你可以把基本布局控制为一个垂直的flex div,但是你让派生类实现this.props.renderCenter,这样它的结果就可以和基本布局结合起来了。

view = () => { // function of BaseListComponent
  let someResult = 100;
  someResult = this.props.view();
  return someResult;
}

同样的思路,this.props.view是通过派生类实现的。

最后在派生类中是这样的:

render() { // function of DeriveComponent; can be MoviesListComponent
  return (
    <BaseListComponent
      renderCenter={this.renderCenter}
      view={this.view}
    >
  );
}

请注意,派生类实际上并不是“派生”或扩展基础组件,它只是将其组合在render() 函数中。所以BaseListComponentMoviesListComponent 都扩展了React.Component(或React.PureComponent 在考虑性能问题时)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多