我有一个简单的组件,它使用像这样的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")
添加满足上述道具界面的this.props.router
,但是打字稿并不能解释这一点,每当我在某个地方使用此组件时,如果我不通过,我会收到错误在道具中向下router
,因此我需要更改为router?: RouterInterface;
,这很好但不理想。
有没有办法解决这个问题,其中typescript会为装饰者注入道具?
答案 0 :(得分: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>
}
}