【问题标题】:Typescript extend React.Component打字稿扩展 React.Component
【发布时间】:2019-09-18 02:05:14
【问题描述】:

@tl;dr
我想在 Typescript 中不使用 HOC / Providers 来扩展 React 组件


好的,这就是交易...
在我的工作场所,我们曾经使用 Vue 和纯 JS...然后我们决定迁移到使用 Typescript 的 React...

我们使用的技术: - 反应 - 打字稿 - 还原 - Redux-Saga

问题是,回到 Vue,我们可以声明如下:

Vue.use(Auth)

在每个 .vue 文件中,我们可以在 script 标签内调用类似的东西:

this.$auth

并且可以访问授权方法。

我想要做的是...创建一个 ReactComponent 的扩展,其中我已经创建了一些我的大多数组件将使用的方法...类似于:

  • auth // 检查用户是否被认证,如果是,获取用户信息
  • route // 给我当前路由,包括查询参数、重定向等... 我现在能想到的只有这两个。

我想在我的 .ts 文件中包含这样的内容:

interface MyProps {
    route: any // don't remember the correct Type
}

class MyComponent<T,S = {},SS = {}> extends React.Component<T,S,SS> {
    $route = () => {
        this.props.route
    }
}

export default withRouter(MyComponent)

并像这样在我的应用程序中调用它:

inteface AnotherProps {

}

class AnotherComponent extends MyComponent<AnotherProps> {
    render() {
        if(this.$route().location.pathname == "/") {
            return <div>Root</div>
        } else {
            return <div>Not Root</div>
        }
    }
}

到目前为止我所尝试的

HOC(高阶组件)

我可以使用 HOC 实现我想要的,但问题是......如果可能的话,我想要两件事。

  • 要将这些新属性存储在 this 而不是 this.props,如果使用 HOC 可以做到这一点,我不知道如何
  • 使用 HOC,我还需要导入基本 Props,如下所示:
import BaseProps from Outterspace;

inteface AnotherProps extends BaseProps{

}

我希望 MyComponentAnotherComponent 内部的逻辑尽可能相互独立...

提供者

与 HOC 相同,我需要将我想要的属性作为 props 传递,并且需要扩展我的 props 接口。

[编辑]

装饰器

有人在 cmets 中说我可以尝试使用 Decoratos,虽然我确实阅读了文档并且听起来很有希望......文档的最后一行让我有点担心..

注意装饰器元数据是一项实验性功能,可能会在未来版本中引入重大更改。

非常感谢您阅读本文^^

【问题讨论】:

    标签: reactjs typescript components


    【解决方案1】:

    如果您使用的是打字稿,那么您可以创建装饰器。

    你可以在你的类之上调用装饰器并添加属性。

    
    @YourAuthDecorator({
      'propertiesForconfiguration': 'value'
    })
    export class ReactClass extends ReactComponent {}
    

    例子:

    function abc() {
      return {};
    }
    
    export function Auth() {
      console.log("-- decorator function invoked --");
      return function (constructor: Function){
        console.log(constructor, 'called');
        constructor.prototype.$auth = abc();
      }
    }
    
    class Sample {
      public prop = 'sample'
    }
    
    @Auth()
    export class Content extends Sample {
    
    }
    
    export const a = new Content();
    

    装饰器的功能是将各种属性附加到 this 实例,让您可以访问各种功能/属性,例如 auth

    您可以在此处阅读有关装饰器的更多信息。 https://www.typescriptlang.org/docs/handbook/decorators.html

    【讨论】:

    • 所以我正在阅读文档,其中有一些非常复杂的东西,比如 reflect.metadata 等等......当我想让 MyComponent 处理任何商店更新?
    • 另外...文档的最后一行让我有点担心:注意装饰器元数据是一项实验性功能,可能会在未来的版本中引入重大更改。
    • Angular 是一个在 typescript 之上编写的主要框架,它在整个框架中大量使用装饰器。
    • 但我无法从 React 更改:c
    • 我已经用一个示例更新了答案,该示例将在运行时将 $auth 属性添加到类原型中。
    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2021-07-16
    • 2017-04-27
    相关资源
    最近更新 更多