首页 > 解决方案 > 导航到组件时声明为接口的道具不可用

问题描述

我有组件,其中道具被声明为接口,并且该组件将类型作为该接口。

例如->

import React, { Component } from 'react'
import { Text, View } from 'react-native'


 interface IDummy{
    name:string;
    age:number;
}
export default class Dummy extends Component<IDummy,any> {
    constructor(props:IDummy){
        super(props)
        console.log('CHeck the props here ',props)
    }
    render() {
        return (
            <View>
                <Text> Just Text </Text>
            </View>
        )
    }
}

现在,如果我将该组件用作其他组件的一部分,例如

<Text>Something</Text>
<Dummy/>

道具名称和年龄工作正常。但是当我想导航到那个组件时,

navigation.navigate('Dummy')

界面中提到的道具不可用。有什么办法可以访问它们???

标签: reactjstypescriptreact-native

解决方案


我会假设你正在使用react-navigation

为了发送参数,您应该使用以下行进行导航:

navigation.navigate('Dummy', {
  name: 'name',
  age: 'age',
});

发送导航事件后,您可以读取以下值:

import React, { Component } from 'react'
import { Text, View } from 'react-native'


interface IDummy{
  name: string;
  age: number;
  route: any;
}

export default class Dummy extends Component<IDummy,any> {

    constructor(props: IDummy){
        super(props)
        console.log('properties from navigation ', props.route.params);
        console.log('Check the props here ',props)
    }

    render() {
        return (
            <View>
                <Text> Just Text </Text>
            </View>
        )
    }
}

有关它的更多信息:将参数传递给路由


推荐阅读