Ilj*_*lja 7 typescript reactjs react-native mobx mobx-react
我有一个简单的组件,使用像这样的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;
Run Code Online (Sandbox Code Playgroud)
基本上@inject("router")补充this.props.router说满足上面的Props接口,但是打字稿不考虑这个,每当我在某个地方使用这个组件时,如果我没有传递router道具,我会得到一个错误,因此我需要改为router?: RouterInterface;哪个好,但不理想.
有没有办法解决这个问题,其中typescript帐户装饰器注入道具?
有一种方法可以解决这个问题。
您可以在单独的接口中声明注入的 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>
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
705 次 |
| 最近记录: |