【发布时间】: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{
}
我希望 MyComponent 和 AnotherComponent 内部的逻辑尽可能相互独立...
提供者
与 HOC 相同,我需要将我想要的属性作为 props 传递,并且需要扩展我的 props 接口。
[编辑]
装饰器
有人在 cmets 中说我可以尝试使用 Decoratos,虽然我确实阅读了文档并且听起来很有希望......文档的最后一行让我有点担心..
注意装饰器元数据是一项实验性功能,可能会在未来版本中引入重大更改。
非常感谢您阅读本文^^
【问题讨论】:
标签: reactjs typescript components