为反应导航道具添加强类型

Mel*_*let 23 typescript react-native react-navigation

我在我的react-native项目(expo)中使用typescript.

该项目使用反应导航,所以在我的屏幕上我可以设置navigationOptions并且我可以访问道具navigation.

现在我正在尝试强类型这些,所以我得到了可用于设置的属性的提示.

interface NavStateParams {
    someValue: string
}

interface Props extends NavigationScreenProps<NavStateParams> {
   color: string
}

class Screen extends React.Component<Props, any> {
    // This works fine
    static navigationOptions: NavigationStackScreenOptions = {
        title: 'ScreenTitle'
    }
    // Does not work
    static navigationOptions: NavigationStackScreenOptions = ({navigation, screenProps }) => ({
        title: navigation.state.params.someValue
    })
}
Run Code Online (Sandbox Code Playgroud)

什么是处理反应导航作为组件道具的最佳方法.

Mah*_*ndi 42

如果您传递的navigationprop 定义为

let navigation = useNavigation()
Run Code Online (Sandbox Code Playgroud)

对于组件,最好的输入方式是:

import {NavigationProp, ParamListBase} from '@react-navigation/native';

navigation: NavigationProp<ParamListBase>
Run Code Online (Sandbox Code Playgroud)

更新:

这是使用最新版本的强导航输入的更好方法@react-navigation6.x

完整示例:

import {NativeStackNavigationProp} from '@react-navigation/native-stack';

type RootStackParamList = {

   ScreenOne: undefined; //current screen

   ScreenTwo: {slug: string}; // a screen that we are 
// navigating to, in the current screen,
// that we should pass a prop named `slug` to it

   ScreenThree: {data: Array<string>};

   ScreenFour: undefined; // a screen that we are navigating to 
// in the current screen, that we don't pass any props to it
};

interface IPageProps {
   navigation: NativeStackNavigationProp<RootStackParamList, 'ScreenOne'>;
}

// Since our screen is in the stack, we don't need to 
// use `useNavigation()` to provide the `navigation` to
// our component, we just need to read it as a prop

function Pdp({navigation}: IPageProps) {
   return ...
}
Run Code Online (Sandbox Code Playgroud)


And*_*ica 30

只需将NavigationType添加到您的道具中,如下所示:

    import { StackNavigator, NavigationScreenProp } from 'react-navigation';

    export interface HomeScreenProps {
      navigation: NavigationScreenProp<any,any>
    };

    export class HomeScreen extends React.Component<HomeScreenProps, object> {

      render() {
        return (
          <View style={styles.container}>       
            <Button
              title="Go to Details"
              onPress={() => this.props.navigation.navigate('Details')}
            />
          </View>
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)


小智 14

最低配置,版本 6.x

import { NavigationProp } from "@react-navigation/native";

interface RouterProps {
    navigation: NavigationProp<any, any>;
}

<TouchableOpacity onPress={() => navigation.navigate('Home')}>
    <Text>Navigate to Home</Text>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)


J. *_*ers 5

这有效:

static navigationOptions = ({ navigation }: NavigationScreenProps) => ({
  ...
})
Run Code Online (Sandbox Code Playgroud)