【问题标题】:Make typescript see props from decorators让打字稿看到装饰者的道具
【发布时间】:2018-04-18 17:33:48
【问题描述】:

我有一个像这样使用 mobx 和装饰器的简单组件

import * as React from "react";
import { observer, inject } from "mobx-react/native";
import { Router as ReactRouter, Switch, Route } from "react-router-native";
import Dashboard from "./_dashboard";
import { RouterInterface } from "../store/_router";

// -- types ----------------------------------------------------------------- //
export interface Props {
  router: RouterInterface;
}

@inject("router")
@observer
class Router extends React.Component<Props, {}> {
  // -- render -------------------------------------------------------------- //
  render() {
    const { router } = this.props;
    return (
      <ReactRouter history={router.history}>
        <Switch location={router.location}>
          <Route path="/" component={Dashboard} />
        </Switch>
      </ReactRouter>
    );
  }
}

export default Router;

基本上@inject("router") 添加了满足上面 Props 接口的this.props.router,但是 typescript 没有考虑到这一点,每当我在某处使用这个组件时,如果我没有在 props 中传递router,就会出错,因此我需要更改为router?: RouterInterface;,这很好,但并不理想。

有没有办法解决这个问题,打字稿说明装饰器注入道具?

【问题讨论】:

  • IMO,没有更好的方法:您使用 TypeScript 的适当设计,为注入的props 定义接口。由于装饰器 @inject 在类定义之后应用(关于 TypeScript 编译),因此类必须提前了解装饰器的效果,至少在类型方面。
  • github.com/mobxjs/mobx-react/issues/256 是关于这类问题的讨论。总结一下:不,目前没有更好的方法。你需要添加吗?到酒店。

标签: reactjs typescript react-native mobx mobx-react


【解决方案1】:

有办法解决它。
您可以在单独的接口中声明注入的道具,然后编写一个 getter 函数。我在这里写过:
https://gist.github.com/JulianG/18af9b9ff582764a87639d61d4587da1#a-slightly-better-solution

interface InjectedProps {
  bananaStore: BananaStore; // ? no question mark here
}

interface BananaProps {
  label: string;
}

class BananaComponent extends Component<BananaProps> {

  get injected(): InjectedProps {
    return this.props as BananaProps & InjectedProps;
  }

  render() {
    const bananas = this.injected.bananaStore.bananas; // ? no exclamation mark here
    return <p>{this.props.label}:{bananas}</p>
  }

}

【讨论】:

    猜你喜欢
    • 2020-01-31
    • 2018-12-16
    • 2018-06-21
    • 2019-07-29
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2018-02-12
    相关资源
    最近更新 更多