gpt4 book ai didi

javascript - react 导航5错误绑定(bind)元素 'navigation'隐式具有 'any' type.ts

转载 作者:行者123 更新时间:2023-12-05 00:24:57 35 4
gpt4 key购买 nike

我是 react 原生的新手。我正在尝试使用 react-navigation 5 实现导航。我有两个屏幕主页和配置文件。这两个组件都收到了导航 Prop ,但 typescript 给了我以下错误

Binding element 'navigation' implicitly has an 'any' type.ts(7031)
如何摆脱这个错误。
先感谢您
注意 - 我正在使用 typescript
应用程序.tsx
import 'react-native-gesture-handler';

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

const Stack = createStackNavigator();

import Home from './screens/home'

const App = () => {

const ProfileScreen = ({}) => {
return <Text>This is Jane's profile</Text>;
};

return (
<NavigationContainer>

<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}

/>
<Stack.Screen name="Profile" component={ProfileScreen} />
</Stack.Navigator>

</NavigationContainer>

);
};
主页.tsx
import React from 'react';
import { Button } from 'react-native';


const Home = ({navigation}) =>{ // error

return (
<Button
title="Go to Jane's profile"
onPress={() =>
navigation.navigate('Profile', { name: 'Jane' })
}
/>
)

}

export default Home;

最佳答案

Typescript 不知道导航类型。
要摆脱此错误,您可以将导航 Prop 键入为 any ( 不建议顺便说一下 )像这样:

/*doing this will make you lose type safety*/
const Home = ({navigation}: {navigation: any}) => {
return ...
}
推荐方法
查看文档 https://reactnavigation.org/docs/typescript/我们可以看到我们需要创建一个对象类型,将路由名称映射到路由的参数,然后将此对象类型作为泛型传递给 createStackNavigator功能。
在屏幕中,我们需要从导航器中导入相应的类型,在您的例子中是 StackNavigator。此类型采用 2 个泛型:参数列表对象类型和当前路由的名称。
// in your case

// App.tsx
import { createStackNavigator } from '@react-navigation/stack';

type RootStackParamList = {
Home: undefined, // undefined because you aren't passing any params to the home screen
Profile: { name: string };
};

const Stack = createStackNavigator<RootStackParamList>();


// Home.tsx
import { StackNavigationProp } from '@react-navigation/stack';
type ProfileScreenNavigationProp = StackNavigationProp<
RootStackParamList,
'Home'
>;

type Props = {
navigation: ProfileScreenNavigationProp;
};

const Home = ({navigation}: Props) =>{
return ...
}

关于javascript - react 导航5错误绑定(bind)元素 'navigation'隐式具有 'any' type.ts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63132548/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com