代码之家  ›  专栏  ›  技术社区  ›  Vencovsky

如何覆盖功能组件中的导航选项?

  •  0
  • Vencovsky  · 技术社区  · 6 年前

    使用类组件覆盖导航选项

    export default class SomeClass extends Component {
    
        static navigationOptions = ({ navigation }) => {
            return {
                title: navigation.getParam('headerTitle'),
            }
        }
    
        componentDidMount() {
            this.props.navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })
        }
    
        ...
    }
    

    但是我如何使用功能组件来实现这个功能??

    export default function SomeFunctionalCompoenent({ navigation }) {
    
        // How and Where do I change the header title ?
    
        useEffect(() => { navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })})
        return (
            ...
        )
    }
    
    1 回复  |  直到 6 年前
        1
  •  19
  •   Vencovsky    5 年前

    您仍然需要在功能组件上定义导航选项。你这样做:

    export default function SomeFunctionalComponent({ navigation }) {
        useEffect(() => { 
            navigation.setParams({ 
                headerTitle: someVariableThatComesFromExternalCall 
            }) 
        }, [])
    }
    
    SomeFunctionalComponent.navigationOptions = ({ navigation }) => {
        return {
            title: navigation.getParam('headerTitle'),
        }
    }
    
        2
  •  2
  •   Andy Lorenz    4 年前

    export default function SomeFunctionalComponent({ navigation }) {
      useEffect(() => { 
        navigation.setOptions({ 
          headerTitle: 'some other title',
        }) 
      }, [])
    }
    

    我用它来访问react上下文——获取用户名和头像,这样我就可以为他们设置一个很好的标题栏。我已经为这个粘贴了代码,以防它对任何人都有帮助:

    import React, { useContext, useEffect } from 'react';
    import UserContext from '../context/UserContext';
    
    const HomeScreen = ({ navigation }) => {
    
      const userContext = useContext(UserContext);
    
      useEffect(() => {
        navigation.setOptions({
          title : userContext.name,
          headerLeft : () => (
            <TouchableOpacity
              onPress={() => {
                navigation.openDrawer();
              }}
            >
              <FastImage
                style={styles.userPhoto}
                resizeMode={FastImage.resizeMode.cover}
                source={{ uri: userContext.avatar }}
              />
            </TouchableOpacity>
          ),
        });
      }, [ userContext ]);
    
      return (
        // etc
      );
    }