Lot*_*sin 11 typescript react-native react-navigation
我有以下两段代码:
自定义头文件.tsx
import { View, StyleSheet, Button } from 'react-native';
import { NavigationScreenProps } from 'react-navigation';
import Icon from 'react-native-vector-icons/Ionicons';
export const CustomHeader = ({ navigation }: NavigationScreenProps) => (
<View style={[styles.container]}>
<Icon
name="md-menu"
size={32}
color="black"
style={{ marginLeft: 10 }}
onPress={() => navigation.openDrawer()}
/>
</View>
);
const styles = StyleSheet.create({
container: {
borderBottomWidth: 2,
height: 70,
paddingTop: 20,
},
});
Run Code Online (Sandbox Code Playgroud)
DetailScreen.tsx
import React from 'react';
import { Text, View, Button, Alert } from 'react-native';
import { NavigationScreenProps } from "react-navigation";
import { CustomHeader } from '../components/Header';
export class ChangeAccountDetailScreen extends React.Component {
render() {
return (
<View style={{ flex: 1 }}>
<CustomHeader navigation={this.props.navigation} />
<Text style={{ fontSize: 20 }}>Profile Screen</Text>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
在详细信息屏幕中,我收到以下错误:
'Readonly<{}> & Readonly<{ children?: ReactNode; 类型上不存在属性“导航” }>'。
我搜索了这个问题,我知道它有一个事实,即我没有在我的 CustomHeader 中声明类型。但是我不知道如何解决这个问题。我对打字稿有点陌生。有人可以向我解释如何解决这种类型的问题吗?
sku*_*ube 17
我可能是错的,但你有没有尝试添加navigation预期的类型
import React from 'react';
import { Text, View, Button, Alert } from 'react-native';
import { NavigationScreenProps } from "react-navigation";
import { CustomHeader } from '../components/Header';
interface Props {
navigation: any
}
export class ChangeAccountDetailScreen extends React.Component<Props> {
render() {
return (
<View style={{ flex: 1 }}>
<CustomHeader navigation={this.props.navigation} />
<Text style={{ fontSize: 20 }}>Profile Screen</Text>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是另一个解决方案,我在接口定义中添加更多详细信息
import React from 'react';
import { Text, View, Button, Alert } from 'react-native';
import {
NavigationParams,
NavigationScreenProp,
NavigationState
} from 'react-navigation';
import { CustomHeader } from '../components/Header';
interface Props {
navigation: NavigationScreenProp<NavigationState, NavigationParams>
}
export class ChangeAccountDetailScreen extends React.Component<Props> {
render() {
return (
<View style={{ flex: 1 }}>
<CustomHeader navigation={this.props.navigation} />
<Text style={{ fontSize: 20 }}>Profile Screen</Text>
</View>
);
}
}Run Code Online (Sandbox Code Playgroud)
小智 7
更现代的答案是按照https://reactnavigation.org/docs/connecting-navigation-prop/useNavigation中的说明使用
import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';
function GoToButton({ screenName }) {
const navigation = useNavigation();
return (
<Button
title={`Go to ${screenName}`}
onPress={() => navigation.navigate(screenName)}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13149 次 |
| 最近记录: |