将道具从组件传递到函数

时间:2019-02-08 11:14:50

标签: reactjs react-native button react-props

我有一个带两个按钮的抽屉式导航器。当我单击登录按钮时,我要从缓存中删除身份验证令牌,然后将屏幕更改为“登录”。

function doSomething(props) {
AsyncStorage.removeItem(AUTH_EMAIL);
AsyncStorage.removeItem(AUTH_TOKEN);
props.navigation.navigate("Login")
}

const CustomContentComponent = (props) => (

<SafeAreaView style={{flex: 1}}>
    <ScrollView>
        <TouchableOpacity style={{flex: 1}}
                          onPress={() => 
props.navigation.navigate("About")}>
            <Text style={mainStyles.blackBigFont}>About</Text>
        </TouchableOpacity>
        <TouchableOpacity style={{flex: 1}}
                          onPress={doSomething.bind(props)}>
            <Text style={mainStyles.blackBigFont}>Login Page</Text>
        </TouchableOpacity>
    </ScrollView>
</SafeAreaView>
);

const AppDrawerNavigator = createDrawerNavigator({
    Dashboard: {
        screen: Dashboard,
    },
    About: {
        screen: About,
    },
},
{
    contentComponent: CustomContentComponent
});

1 个答案:

答案 0 :(得分:0)

您需要将函数放入组件中,并使用ES6语法作为方法,然后您无需绑定this

const CustomContentComponent = props => {
  doSomething = () => {
    AsyncStorage.removeItem(AUTH_EMAIL);
    AsyncStorage.removeItem(AUTH_TOKEN);
    this.props.navigation.navigate("Login");
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <ScrollView>
        <TouchableOpacity
          style={{ flex: 1 }}
          onPress={() => props.navigation.navigate("About")}
        >
          <Text style={mainStyles.blackBigFont}>About</Text>
        </TouchableOpacity>
        <TouchableOpacity style={{ flex: 1 }} onPress={doSomething}>
          <Text style={mainStyles.blackBigFont}>Login Page</Text>
        </TouchableOpacity>
      </ScrollView>
    </SafeAreaView>
  );
};