TSLint:Property' params'类型' NavigationState'

时间:2018-03-08 18:26:59

标签: typescript react-native react-navigation

我在react-native开发中使用typescript。我将params传递给navigate函数进行筛选。

this.props.navigation.navigate("NextScreen", { title: "title" })

NextScreen我通过this.props.navigation.state.params.title访问参数,但我params出现了tslint错误。

TS2339:Property 'params' does not exist on type 'NavigationState'.

这是一些代码。

import { NavigationInjectedProps } from "react-navigation";
interface OwnProps {
}
interface OwnState {
}

type Props = NavigationInjectedProps & OwnProps;

class NextScreen extends React.Component<Props, OwnState> {
    ...
    public render() {
        // tslint error occurs in this line.
        const { title } = this.props.navigation.state.params;
        ...
    }
}

我假设我应该定义传递道具的类型但是什么是正确的方法?

2 个答案:

答案 0 :(得分:3)

我用这种方式解决了,但我不确定这是不是最好的方法。 在研究原始代码时,我使用自定义类型navigation重新定义NavigationScreenProp<NavStateParams>

import { NavigationInjectedProps, NavigationScreenProp, NavigationState } from "react-navigation";
...
interface ParamType {
  title: string;
}
interface StateParams extends NavigationState {
  params: ParamType;
}
interface OwnProps {
  navigation: NavigationScreenProp<StateParams>;
}

type Props = OwnProps & NavigationInjectedProps;

答案 1 :(得分:0)

像这样提取params

const {params} = this.props.navigation.state;

const title = params.title