如何在React-native中使导航标题标题动态化?

时间:2019-05-21 16:25:45

标签: javascript react-native

在我的React本机项目中,我正在使用抽屉式导航。我已经在“抽屉”导航中设置了一些屏幕,并且在“抽屉”导航之外设置了一些屏幕。 我为此设置声明了一个名为 HomeDrawer 的类。这是该类的代码。

HomeDrawer.js

 class NavigationDrawerStructure extends React.Component {

      constructor() {
        super();
        this.state = {
          ModalVisibleStatus: false,   
        }
      };

      static navigationOptions = {
        header: null ,
      };

      toggleDrawer = () => {
        this.props.navigationProps.toggleDrawer();
      };

      render() {
        return (

          <View style={{ flexDirection: 'row', marginLeft:5 }}>

            <TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
              <Image style={{width:20, height:20, margin:5, justifyContent:'center'}} source={require('../assets/menu.png')} />
            </TouchableOpacity>

          </View>

        );
      }
    }
    const FirstActivity_StackNavigator = createStackNavigator({
      First: {
        screen: HomeScreen,
        navigationOptions: ({ navigation }) => ({
          title: 'Home',
          headerLeft: <NavigationDrawerStructure navigationProps={navigation} />
          ),

          headerStyle: {
            backgroundColor: '#FF9800',
          },
          headerTintColor: '#fff',
        }),

      },


      ScreenInternal: {
        screen: BookDetails,
        navigationOptions: ({ navigation }) => ({
          title: 'Screen With Navigation Drawer',
          headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,

          headerStyle: {
            backgroundColor: '#FF9800',
          },
          headerTintColor: '#fff',
        }),
      },


    });

    const Screen2_StackNavigator = createStackNavigator({
      Second: {
        screen: CategoryBrowse,
        navigationOptions: ({ navigation }) => ({
          title: 'Create Note',
          headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,

          headerStyle: {
            backgroundColor: '#FF9800',
          },
          headerTintColor: '#fff',
        }),
      },
    });



    const Drawer = createDrawerNavigator({


      Screen1: {
        screen: FirstActivity_StackNavigator,
        navigationOptions: {
          drawerLabel: 'Home',
          drawerIcon: (
            <Icon name='home' size={25}                        
            />
          )

        },
      },

      Screen2: {
        screen: Screen2_StackNavigator,
        navigationOptions: {
          drawerLabel: 'Category',
          drawerIcon: (
            <Image  source={require('../assets/splash.png')}  
            style={{height:25, width:25,}}                          
            />
          )
        },
      },

    },


    {
      contentComponent: CustomSidebarMenu,
      //Sidebar width
      drawerWidth: Dimensions.get('window').width - 130,
    },


    );



    const Drawer2 = createDrawerNavigator({
      Screen1: {
        screen: FirstActivity_StackNavigator,
        navigationOptions: {
          drawerLabel: 'Home',

          drawerIcon: (
            <Icon name='home' size={25}                         
            />
          )

        },
      },

      Screen2: {
        screen: Screen2_StackNavigator,
        navigationOptions: {
          drawerLabel: 'Category',
          drawerIcon: (
            <Image  source={require('../assets/splash.png')}  
            style={{height:25, width:25,}}

            />
          )
        },
      },


    },


    {

      drawerType: 'back',
        drawerPosition: 'right',
        drawerWidth: 200,
        drawerBackgroundColor: 'orange',
      //For the Custom sidebar menu we have to provide our CustomSidebarMenu
      contentComponent: CustomSidebarMenu,
      //Sidebar width
      drawerWidth: Dimensions.get('window').width - 130,
    },


    );


    const DrawerNavigatorExample = createStackNavigator({
      Drawer: { screen: Drawer, navigationOptions: { header: null } },
      BookDetails: {
        screen: BookDetails,
        navigationOptions: { title: 'Book Details' },
      },

      CartPage: {
        screen: CartPage,
        navigationOptions: { title: 'Cart Page' },
      },

    },

    );

在上面的代码中,您可以看到我有一个名为“ HomeScreen”的内部屏幕和一个名为“ BookDetails ”的抽屉的外部屏幕。我还为屏幕设置了 navigationOptions 标题。

现在,在主屏幕中,我有一个click事件,通过按下e元素,我可以传递一个值并启动外部屏幕“ BookDetails ”。这是该代码-

 <TouchableOpacity style={{flexDirection:'row'}}
          onPress={() => this.props.navigation.navigate('BookDetails', {
            JSON_ListView_Clicked_Item: item.id,
          })}

  >

现在,在BookDetails屏幕中,我想根据我从HomeScreen接收到的值更改导航标题的标题。

这是我的 BookDetails 屏幕的代码-

BookDetails.js

class BookDetails extends Component {

  constructor() {
    super()
    this.state= {
        dataSource : [],
        isLoading: true,
        bookId: '',
        responseDetails:'',
        loading: true
    }
}

async componentDidMount() {
  const { navigation } = this.props;
  this.focusListener = navigation.addListener("didFocus", () => {
    this.getBookDetailsApi(); 
  });

   this.setState({
     bookId:(
      this.props.navigation.state.params.JSON_ListView_Clicked_Item
      ? this.props.navigation.state.params.JSON_ListView_Clicked_Item
      : 'No Value Passed'
     )
   })
}

async componentWillMount() {
  await Font.loadAsync ({
    Roboto: require('native-base/Fonts/Roboto.ttf'),
    Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf')
  });
  this.setState({loading:false});
}

getBookDetailsApi() {
  const url = 'my url';
   return fetch(url, {
    method: 'GET',
    headers: new Headers({
      'Content-Type' : 'application/json',
      'app_api_key': APP_API_KEY,

    })
  })
   .then((response)=> response.json() )
  .then((responseJson) => {
   console.log('####:'+responseJson.nameEnglish)
    this.setState({
      responseDetails: responseJson,
      isLoading: false,    
    })
  })
  .catch((Error) => {
    console.log(Error)
  });

};

}

  render() {  
    if(this.state.loading) {
      return(
        <Root>
          <AppLoading/>
        </Root>
      );

    }

    return (
      <View style={styles.container}>
          <TouchableOpacity 
            onPress = {()=>{
              this.props.navigation.navigate('CartPage')
            }}
          >
            <Text style={styles.title}>Hello Splash</Text>

          </TouchableOpacity>   
      </View>
    );
  }
}

export default BookDetails;

现在,我需要一种解决方案来保持 BookDetails 屏幕导航标题的动态,并根据从 HomeScreen 接收到的值不断对其进行更改。因此,如果有人提供解决方案,那将非常好。

enter image description here

0 个答案:

没有答案