Заголовок Dynami c в реагирующей навигации - PullRequest
0 голосов
/ 09 апреля 2020

Я использую функциональный подход с react-navigation v5.0.0, и у меня есть стековый навигатор, который содержит:

App.js

<Stack.Screen
   name="Profil"
   component={Profile}
   options={{
      headerStyle: {
         backgroundColor: '#2270b9'
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
         color: 'white'
      },
      headerRight: () => (
         <View style={{ flex: 1, flexDirection: 'row' }}>
            <Ionicons
               style={{ color: 'white', marginRight: 15, marginTop: 5 }}
               size={32}
               onPress={() => { _sendMessage(...) }}            // <--- problem is here
               name="ios-mail"
               backgroundColor="#CCC"
            />
         </View>
      )
   }}
/>

Компонент профиля выглядит примерно так:

Profile.js

export default function Profile({ route, navigation }) {
   const { profile } = route.params;

   return (
      <SafeAreaView style={styles.container}>
         <View style={styles.container}>
            <ScrollView contentContainerStyle={styles.contentContainer}>
   [...]

Теперь проблема в том, что Profile инициализируется с объектом полезной нагрузки («профиль»), когда открывается профиль:

Search.js / Visitors.js

navigation.navigate('Profil', { profile });

И проблема в том, что кнопка отправки, которая добавляется в App.js нужен объект профиля, который передается в Profile.js в качестве параметра маршрута, но он недоступен в App.js.

Как я могу таким образом создать кнопку заголовка в компоненте Profile, поэтому Я могу получить доступ к объекту профиля?

Ответы [ 2 ]

1 голос
/ 10 апреля 2020

На самом деле, я нашел способ обойти это - это можно решить, добавив заголовок в Profile.js (где объект доступен), а не в App.js.

Так что я просто удалил код для headerRight в App.js и вместо этого вставил в Profile.js:

export default function Profile({ route, navigation }) {
   const { profile } = route.params;

   React.useLayoutEffect(() => {
      navigation.setOptions({
         headerRight: () => (
            <View style={{ flex: 1, flexDirection: 'row' }}>
               <Ionicons
                  style={{ color: 'white', marginRight: 15, marginTop: 5 }}
                  size={32}
                  onPress={_onSendMessage}
                  name="ios-mail"
                  backgroundColor="#CCC"
                  enabled={ profile && profile.core ? true : false}
               />
            </View>
         )
      });
    }, []);

Таким образом, независимо от того, откуда открыт Profile.js, обратный вызов кнопки будет иметь доступ к текущий объект профиля, который находится в состоянии Profile.js '.

1 голос
/ 09 апреля 2020

Вы можете попробовать изменить опцию опций, чтобы взять маршрут в качестве параметра, например, так:

options={({ route: { params: { profile } } }) => ({
  /** use profile here */
})

Чтобы поместить его в контекст вашего приложения. js, обратите внимание, как опции это функция, принимающая {route } в качестве параметра и возвращая ваш объект параметров.

<Stack.Screen
   name="Profil"
   component={Profile}
   options={({ route: { params: { profile } } }) => ({ // <- Note that options in now a function
      headerStyle: {
         backgroundColor: '#2270b9'
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
         color: 'white'
      },
      headerRight: () => (
         <View style={{ flex: 1, flexDirection: 'row' }}>
            <Ionicons
               style={{ color: 'white', marginRight: 15, marginTop: 5 }}
               size={32}
               onPress={() => { _sendMessage(profile) }} // <--- you can use profile here
               name="ios-mail"
               backgroundColor="#CCC"
            />
         </View>
      )
   })}
/>

документы по реактивной навигации

...