#typescript #react-native #react-native-navigation
Вопрос:
я пытаюсь перейти на другой экран из компонента, размещенного на главной странице, но приведенный ниже код не работает. Я думаю, что перепробовал все решения, которые нашел в Интернете, но ни одно из них, похоже, не работает. (Кнопка на главной странице работает)
Домашняя страница:
import * as React from 'react';
import { StyleSheet,View ,Button} from 'react-native';
import RecipeButton from '../components/recipeButton';
import recipes from '../../assets/data/recipes';
import { StatusBar } from 'expo-status-bar';
export default function HomePage({navigation}: {navigation: any}) {
return(
<View style={styles.container}>
<StatusBar style="light" backgroundColor="black" translucent={false} />
<FlatList
style={{width:'100%'}}
data={recipes}
renderItem={({ item }) => <RecipeButton item={item} />}
/>
<Button title='navigate to recipe' onPress={() => {
navigation.navigate("Recipe")
}} />
</View>
)
}
сценарий компонента:
import React from 'react';
import { Image, View, Text, Pressable} from 'react-native';
import { FontAwesome } from '@expo/vector-icons';
import styles from './styles';
interface recipeButtonProps {
item: {
image: string,
}
}
const RecipeButton = ({ item }: recipeButtonProps, {navigation}: {navigation: any}) => {
const onPress = () => {
navigation.navigate("Recipe")
}
return (
<View style={styles.root}>
<Image style={styles.image} source={{ uri: item.image }} />
<Pressable
style={({pressed}) => [
{backgroundColor: pressed ? '#D3D3D3' : 'white'},
styles.nonImageContainer
]}
onPress={() => {
onPress();
}}>
</Pressable>
</View>
);
};
export default RecipeButton;
Комментарии:
1. Попробуйте передать свойство навигации, например
<FlatList style={{width:'100%'}} data={recipes} renderItem={({ item }) => <RecipeButton item={item} navigation={navigation} />} />
2. это не работает Тип » {элемент: { идентификатор: строка; пользователь: { идентификатор: строка; имя: строка; изображение: строка; }; имя: строка; изображение: строка; рецепт: строка; требуется: строка; рейтинг: число; количество оценок: число; Необходимое время: строка; сложность: строка; }; навигация: любая; }» не присваивается типу «Встроенные атрибуты и кнопки рецепта». Свойство «навигация» не существует для типа «Встроенные атрибуты и кнопки рецептов».
Ответ №1:
Я думаю RecipeButton
, что это не в контексте навигатора, поэтому он не получает navigation
поддержки.
Попробуйте использовать useNavigation()
крючок вот так:
...
import { useNavigation } from '@react-navigation/native';
...
const RecipeButton = ({ item }: recipeButtonProps) => {
const navigation = useNavigation();
const onPress = () => {
navigation.navigate("Recipe")
}
...
};
export default RecipeButton;