反应本机navigationOptions调用函数错误

时间:2018-11-06 05:50:27

标签: react-native react-navigation

navigationOptions内调用函数时出错。

static navigationOptions = {
    tabBarIcon: ({ tintColor })=> (
      <Icon name='ios-add-circle' style={{ color: tintColor}} />
    ),
    tabBarOnPress: () => {
      this.callingFun();
    },
  }

  callingFun = ()=> {
    console.log('tabBarOnPress:');
  }

错误:

error image

4 个答案:

答案 0 :(得分:2)

您不能在静态对象属性中调用callingFun。我想你想要这个

static navigationOptions = ({navigation}) => {
    return {
        tabBarIcon: ({ tintColor }) => (
            <Icon name='ios-add-circle' style={{ color: tintColor }} />
        ),
        tabBarOnPress: () => {
            navigation.getParam('callingFun')();
        },
    }
}

callingFun = () => {
    console.log('tabBarOnPress:');
}

componentDidMount() {
    const { navigation } = this.props
    navigation.setParams({
        callingFun: this.callingFun,
    })
}

答案 1 :(得分:0)

const BottomTab = createMaterialTopTabNavigator({
Active:OnlineStack
}, {

    tabBarPosition: 'top',
    tabBarOptions: {
        activeTintColor: 'gray',
        inactiveTintColor: 'white',
        labelStyle: {
            fontSize: 12,
            fontFamily: "Choco_Cooky"
          }, 
        style: {
            backgroundColor: 'black',
            borderWidth: 1,
            borderBottomWidth:0,
            borderColor: 'gray',
          },
    }
    /* Other configuration remains unchanged */
 }
);


 OnlineStack.navigationOptions = ({navigation})=>{
        let { routeName } = navigation.state.routes[navigation.state.index];
        let navigationOptions = {};
        header: null;
        if (routeName === 'Home') {
        navigationOptions.tabBarVisible = false;
        }
        return navigationOptions;
        }

答案 2 :(得分:0)

静态方法调用是在类而不是实例上进行的。没有办法在静态方法中引用它。使用类的名称只能达到静态方法。

export default class MediaTab extends React.Component {
  static navigationOptions = {
    tabBarIcon: ({ tintColor })=> (
      <Icon name='ios-add-circle' style={{ color: tintColor}} />
    ),
    tabBarOnPress: () => {
      MediaTab.callingFun();
    },
  }

  static callingFun = () => {
    console.log('tabBarOnPress:');
  }
}

答案 3 :(得分:0)

我已通过以下方式解决了该问题:

static navigationOptions = ({ navigation }) => {
    return {
        headerRight: () => (

            <TouchableOpacity
                onPress={navigation.getParam('onPressSyncButton')}>
                <Text>Sync</Text>
            </TouchableOpacity>
        ),
    };
};

componentDidMount() {
    this.props.navigation.setParams({ onPressSyncButton: this._onPressSyncButton });
}

_onPressSyncButton = () => {
     console.log("function called");
}