我有一个像这样使用 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
满足上面的 Props 接口(interface),但是 typescript 没有考虑到这一点,每当我使用它时如果我不在 props 中传递 router
,我会在某个地方出现错误,因此我需要更改为 router?: RouterInterface;
这很好,但并不理想。
有没有办法解决 typescript 说明装饰器注入(inject) Prop 的问题?
最佳答案
有办法解决它。
您可以在单独的接口(interface)中声明注入(inject)的 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>
}
}
关于reactjs - 让 typescript 看到装饰器的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47138906/