我有一个简单的组件,它使用 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
,但是打字稿没有考虑到这一点,每当我在某处使用此组件时,如果我不在 props 中传递router
,我都会出错,因此我需要更改为 router?: RouterInterface;
这很好,但并不理想。
有没有办法解决这个问题,打字稿帐户是装饰者注入道具的?
有一种方法可以解决它。
您可以在单独的接口中声明注入的 props,然后编写一个 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>
}
}