【问题标题】:TSLint: Property 'params' does not exist on type 'NavigationState'TSLint:“NavigationState”类型上不存在属性“params”
【发布时间】:2018-08-17 05:09:21
【问题描述】:

我在 react-native 开发中使用 typescript。我通过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;
        ...
    }
}

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

【问题讨论】:

  • 您需要显示所有相关代码。 AFAICT 不足以回答您的问题。
  • 所以为了清楚起见,脚本确实有效,但是您得到了代码分析标志?
  • 是的,我收到 tslint 错误,而不是运行时错误或崩溃。
  • @Smart Solutions,你应该结合自己的道具和导航道具

标签: typescript react-native react-navigation


【解决方案1】:

像这样提取参数

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

const title = params.title

【讨论】:

    【解决方案2】:

    我通过这种方式解决了,但我不确定这是否是最好的方式。 研究原始代码,我用自定义类型NavigationScreenProp&lt;NavStateParams&gt;重新定义了navigation

    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;
    

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2017-09-02
      • 2020-10-29
      • 2019-09-14
      • 2019-04-06
      • 2021-01-09
      • 2021-07-10
      • 1970-01-01
      相关资源
      最近更新 更多