React Native onPress автоматически вызывается с помощью навигации - PullRequest
0 голосов
/ 19 июня 2020

Я бы подумал, что onPress должен работать только тогда, когда он запускается событием касания. Раньше это было так, но когда я использовал withNavigation на экране не в StackNavigator, onPress, кажется, рендерил автоматически.

HomeScreen. js

function mapStateToProps(state) {
  return { action: state.action };
}

function mapDispatchToProps(dispatch) {
  return {
    openMenu: () =>
      dispatch({
        type: "OPEN_MENU",
      }),
  };
}

class HomeScreen extends React.Component {
  constructor(props) {
    super(props);
    this.notificationVisibility = this.notificationVisibility.bind(this);
    this.dashboardVisibility = this.dashboardVisibility.bind(this);
    this.state = {
      scale: new Animated.Value(1),
      opacity: new Animated.Value(1),
      user: "",
      notificationvisibility: true,
      dashboardvisibility: false,
    };
  }

  static navigationOptions = {
    headerShown: false,
  };

  componentDidUpdate() {
    this.toggleMenu();
  }

  async componentDidMount() {
    StatusBar.setBarStyle("dark-content", true);
    let user = await Auth.currentAuthenticatedUser();
    this.setState({ user: user.username });
    console.log("logged in!");
  }

  toggleMenu = () => {
    if (this.props.action == "openMenu") {
      Animated.timing(this.state.scale, {
        toValue: 0.9,
        duration: 300,
        easing: Easing.in(),
      }).start();
      Animated.spring(this.state.scale, {
        toValue: 0.5,
      }).start();

      StatusBar.setBarStyle("light-content", true);
    }

    if (this.props.action == "closeMenu") {
      Animated.timing(this.state.scale, {
        toValue: 1,
        duration: 300,
        easing: Easing.in(),
      }).start();
      Animated.spring(this.state.scale, {
        toValue: 1,
      }).start();

      StatusBar.setBarStyle("dark-content", true);
    }
  };

  notificationVisibility = () => {
    console.log("pressed!");
    this.setState({
      notificationvisibility: true,
      dashboardvisibility: false,
    });
  };

  dashboardVisibility = () => {
    console.log("pressed!");
    this.setState({
      notificationvisibility: false,
      dashboardvisibility: true,
    });
  };

  render() {
    return (
      <RootView>
        <Menu />
        <AnimatedContainer
          style={{
            transform: [{ scale: this.state.scale }],
            opacity: this.state.opacity,
          }}
        >
          <SafeAreaView>
            <ScrollView style={{ height: "100%" }}>
              <HeaderBox>
                <TitleBar>
                  <Title>Welcome back,</Title>
                  <Name>{this.state.user}</Name>
                  <TouchableOpacity
                    onPress={this.props.openMenu}
                    style={{ position: "absolute", right: 30 }}
                  >
                    <Avatar source={require("../../assets/profilepic.jpg")} />
                  </TouchableOpacity>
                </TitleBar>

                <Searchbar>
                  <Ionicons
                    name="ios-search"
                    size={20}
                    color="#00263A"
                    style={{ padding: 10 }}
                  />
                  <TextInput />
                </Searchbar>
              </HeaderBox>

              <MenuNav>
                <TouchableOpacity onPress={this.notificationVisibility}>
                  <Navigation>Notifications</Navigation>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.dashboardVisibility}>
                  <Navigation>Dashboard</Navigation>
                </TouchableOpacity>
              </MenuNav>

              <ScrollView
                style={{
                  flexDirection: "row",
                  padding: 20,
                  paddingLeft: 12,
                  paddingTop: 65,
                  paddingBottom: 35,
                }}
                horizontal={true}
                showsHorizontalScrollIndicator={false}
              >
                {logos.map((logo, index) => (
                  <Notification
                    key={index}
                    image={logo.image}
                    text={logo.text}
                    text2={logo.text2}
                  />
                ))}
              </ScrollView>

              {this.state.dashboardvisibility ? <DashboardHome /> : null}
              {this.state.notificationvisibility ? <NotificationHome /> : null}
            </ScrollView>
          </SafeAreaView>
        </AnimatedContainer>
      </RootView>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);

MenuScreen. js

class Menu extends React.Component {
  constructor(props) {
    super(props);
    this.signOut = this.signOut.bind(this);
  }

  state = {
    top: new Animated.Value(screenHeight),
  };

  async signOut() {
    // const { navigation } = this.props;
    await AsyncStorage.getAllKeys().then(AsyncStorage.multiRemove);
    Auth.signOut();
    this.props.navigation.navigate("AuthLoading");
  }

  componentDidMount() {
    this.toggleMenu();
  }

  componentDidUpdate() {
    this.toggleMenu();
  }

  toggleMenu = () => {
    if (this.props.action == "openMenu") {
      Animated.spring(this.state.top, {
        toValue: 54,
      }).start();
    }

    if (this.props.action == "closeMenu") {
      Animated.spring(this.state.top, {
        toValue: screenHeight,
      }).start();
    }
  };

  render() {
    return (
      <AnimatedContainer style={{ top: this.state.top }}>
        <Cover>
          <Image source={require("../../assets/backgroundimg.png")} />
          <Title>Vanessa Wong</Title>
          <Subtitle>filler</Subtitle>
        </Cover>
        <TouchableOpacity
          onPress={this.props.closeMenu}
          style={{
            position: "absolute",
            top: 120,
            left: "50%",
            marginLeft: -22,
            zIndex: 1,
          }}
        >
          <CloseView>
            <Ionicons name="ios-close" size={44} color="#000000" />
          </CloseView>
        </TouchableOpacity>
        <Content>
          <MenuItem icon="ios-settings" title="Account" text="settings" />
          <MenuItem icon="ios-card" title="Billing" text="payments" />
          <NavigationContainer ref={navigationRef}>
            <TouchableOpacity onPress={() => this.signOut()}>
              <MenuItem icon="ios-exit" title="Logout" text="see you soon!" />
            </TouchableOpacity>
          </NavigationContainer>
        </Content>
      </AnimatedContainer>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withNavigation(Menu));

Что-то не так как я звоню onPress={this.props.openMenu} в HomeScreen. js? Я пробовал onPress={()=>this.props.openMenu} безрезультатно.

1 Ответ

0 голосов
/ 19 июня 2020

Прежде всего, я хотел поприветствовать наше сообщество ^ _ ^,
, и я действительно хочу sh, что вы добьетесь успеха здесь.

По поводу вашего вопроса попробуйте прокомментировать его два и сообщите мне, есть ли обновления.

  componentDidMount() {
       // this.toggleMenu();
      }

  componentDidUpdate() {
   // this.toggleMenu();
  }

Всего наилучшего

...