打字稿扩展React.Component

时间:2019-04-29 12:34:21

标签: reactjs typescript components

@tl; dr
我想扩展一个React组件而不在Typescript中使用HOC /提供程序


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

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

事情是,回到Vue,我们可以声明类似以下内容:

Vue.use(Auth)

在每个.vue文件中,在脚本标记内,我们可以调用类似以下内容的

this.$auth

并可以访问授权方法。

我想做的是...创建ReactComponent的扩展,我已经在其中创建了大多数Component都会使用的一些方法...类似

  • 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{

}

并且我希望 MyComponent AnotherComponent 内部的逻辑尽可能彼此独立...

提供商

与HOC一样,我需要将所需的属性作为prop传递,并且需要扩展props接口。

[编辑]

装饰器

有人在评论中说我可以尝试使用Decoratos,尽管我确实阅读了文档,但听起来很有希望...文档的最后一行有点让我担心。

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

非常感谢您阅读本文^^

1 个答案:

答案 0 :(得分:0)

如果使用打字稿,则可以创建装饰器。

您可以在类顶部调用装饰器并添加属性。


@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();

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

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

相关问题