React-Native, Dynamic ReactNavigation title

此生再无相见时 提交于 2020-05-14 11:42:22

问题


I have a screen that it's title should set from AsyncStorage and many screens are navigating to this screen (so I don't want pass the title everywhere I'm navigating).

As navigationOptions is static I'm not able to use this.state and also can't set it's title by reading from AsyncStorage (because AsyncStorage is Async :)

How can I change the title inside the screen itself in such a situation?


回答1:


You can use setParams navigation action to set the title after async function ends.

Example

class SomeScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state;

    return {
      title: params ? params.screenTitle: 'Default Screen Title',
    }
  };

  componentDidMount() {
    AsyncStorage.getItem('someValueToGet').then((value) => {
      this.props.navigation.setParams({screenTitle: value})
    });
  }

  // OR You can wait for the someValueToGet

  async componentDidMount() {
    const value = await AsyncStorage.getItem('someValueToGet');
    this.props.navigation.setParams({screenTitle: value})
  }

  /* render function, etc */
}


来源:https://stackoverflow.com/questions/50084311/react-native-dynamic-reactnavigation-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!