簡體   English   中英

如何在底部導航欄中訪問類的this.state(React Native)

[英]How to access this.state of a class in Bottom navigation bar (React Native)

我想在底部的導航欄中訪問MainAct類的this.state。 這樣,當this.state更新時,導航欄就會重新渲染

這是我的代碼。

我想訪問底部導航欄“ MainAct”中的“ this.state.data”。 (或其他選擇)

並且將createMaterialBottomTabNavigator導出為默認行嗎?

 //jshint ignore: start import React, { Component } from 'react'; import { View, Text, Image, } from 'react-native'; window.navigator.userAgent = 'react-native'; import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs'; class MainAct extends Component { constructor(props) { super(props); this.state = { data: 'Hello World' } } render() { return ( <View style={styles.parent}> <Text>{this.state.data}</Text> </View> ); } } export default createMaterialBottomTabNavigator({ Screen1: { screen: Screen1, navigationOptions: { tabBarLabel: 'Screen1', tabBarIcon: ({ tintColor }) => ( <Image source={me} style={{ width: 20, height: 20 }} /> ) } }, Screen2: { screen: Screen2, navigationOptions: { tabBarLabel: 'Screen2', tabBarIcon: ({ tintColor }) => ( <Image source={Chat} style={{ width: 20, height: 20 }} /> ) } }, Screen3: { screen: Screen3, navigationOptions: { tabBarLabel: 'Screen3', tabBarIcon: ({ tintColor }) => ( <Image source={homeIcon} style={{ width: 20, height: 20 }} /> ) } }, MainAct: { screen: MainAct, navigationOptions: { tabBarLabel: 'MainAct', tabBarIcon: ({ tintColor }) => ( <View> <View style={{ display: 'flex'}}> <View style={{ position: 'absolute', right: -8, top: -5, backgroundColor: '#4CAF50', borderRadius: 200, height: 14, paddingLeft: 4, paddingRight: 4, zIndex: 5 }}> <Text style={{ alignSelf: 'center', marginTop: 0, color: '#FFFFFF', fontSize: 10 }}>{this.state.data}</Text> </View> </View> <Image source={noti} style={{ width: 20, height: 20 }} /> </View> ) } }, Screen5: { screen: Screen5, navigationOptions: { tabBarLabel: 'Screen5', tabBarIcon: ({ tintColor }) => ( <Image source={new1} style={{ width: 20, height: 20 }} /> ) } }, }, { initialRouteName: 'MainAct', activeColor: '#000000', inactiveColor: '#000000', barStyle: { backgroundColor: '#FFFFFF', height: 60, elevation: 0, shadowColor: 0 }, }); 

如果您的BottomNavigator必須訪問屏幕狀態,則您的狀態可能在錯誤的位置。 您應該考慮為應用程序設置一個全局狀態,因為React中的數據流應該是單向的,並且父組件不應該僅訪問子狀態。

有多種方法可以執行此操作,例如reduxmobxhooks或任何您喜歡的狀態管理庫。 如果您具有全局狀態,則BottomNavigatorMainAct都可以訪問它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM