React Native Elements Button不会更改禁用状态

时间:2019-04-04 13:09:06

标签: javascript react-native react-native-android react-native-ios

所以这个问题使我发疯!我一周前从本地人开始使用react-native。我设置了状态,但是尽管日志正确,但按钮仍然是名称。这是_addNamePage()[l。 226]。我将提供完整的代码,也许有一些我不认识的依赖项。

编辑:

因此,我的viewpager可能会出现问题,因为如果我在直接渲染方法中使用它,它就可以正常工作。

import React, { Component } from "react";
import {
  View,
  Image,
  StyleSheet,
  Text,
  AppRegistry,
  Alert,
  YellowBox,
  Animated,
  UIManager,
  LayoutAnimation,
  Platform,
  SafeAreaView,
  KeyboardAvoidingView
} from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import Images from "../assets/img/images";
import HeaderText1 from "../symbols/text/headerText1";
import { ThemeProvider, Input, Divider, Button } from "react-native-elements";
import Theme from "../assets/themes";
import DefaultButton from "../symbols/buttons/defaultButton";
import GenderButton from "../symbols/buttons/genderButton";
import GENDERS from "../scripts/profile/gender";
import GlobalSettings from "../globalSettings";

import { strings } from "../../locales/i18n";
import ProgressBar from "react-native-progress/Bar";
import FadeInView from "../symbols/helper/fadeInView";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
  listenOrientationChange as loc,
  removeOrientationListener as rol
} from "react-native-responsive-screen";

import GeneralStatusBarColor from "../symbols/statusBar/GeneralStatusBarColor";

import {
  PagerTabIndicator,
  IndicatorViewPager,
  PagerTitleIndicator,
  PagerDotIndicator,
  ViewPager
} from "rn-viewpager";

import colors from "../assets/colors";
import images from "../assets/img/images";

export default class StartScreen extends Component {
  static navigationOptions = {
    header: null
  };

  constructor(props) {
    super(props);

    // Configurations
    this.defaultLogoHeight = 100;
    this.expandedLogoHeight = 70;

    this.defaultLogoWidth = 300;
    this.expandedLogoWidth = 200;

    this.pagePosition = 0;

    this.expanded = false;

    this.state = {
      /* Profile */
      userGender: null,
      userName: null,
      /* Name Setup page */
      canContinueWithName: false,
      /* View */
      setUpProgress: 0,
      viewPagerItems: [],
      progressBarHeight: new Animated.Value(0),
      progressBarHeight_Value: 0,
      viewPagerPosition: 0,
      logoHeight: this.defaultLogoHeight,
      logoWidth: this.defaultLogoWidth
    };

    this.addInitialPage = this._addInitialPage.bind(this);

    this._onPageScroll = this._onPageScroll.bind(this);
    this._onPageSelected = this._onPageSelected.bind(this);

    if (Platform.OS === "android") {
      UIManager.setLayoutAnimationEnabledExperimental &&
        UIManager.setLayoutAnimationEnabledExperimental(true);
    }

    /* Register button events */
    this._onLoginButtonPressed = this._onLoginButtonPressed.bind(this);
    this._onContinueNameSetup = this._onContinueNameSetup.bind(this);
    this._onMaleButtonPressed = this._onMaleButtonPressed.bind(this);
    this._onFemaleButtonPressed = this._onFemaleButtonPressed.bind(this);
    this._handeUserNameChange = this._handeUserNameChange.bind(this);

    /* [TEST] */
    /*
    setTimeout(() => {
      this._enableSetUpMode(true);
    }, 2000);
    */
  }

  componentDidMount() {
    this._addInitialPage();
  }

  componentDidUpdate(prevProps, prevState) {
    /* Log progress
    console.log(
      "Prev Set Up Progress " +
        prevState.setUpProgress +
        " Now " +
        this.state.setUpProgress
    );
    */

    /* Add name page */
    if (prevState.setUpProgress < 1 && this.state.setUpProgress == 1) {
      this._addNamePage();
      this._goToPageWithDelay(1);
    }
  }

  _goToPageWithDelay(page) {
    setTimeout(() => this._goToPage(page), 100);
  }

  _goToPage(page) {
    this._viewPager.setPage(page);
  }

  /* #region Initial Page */

  _addInitialPage() {
    console.log("Adding initial page to ViewPager");
    this.setState(state => ({
      viewPagerItems: [
        ...state.viewPagerItems,
        <View key={"initialPage"} style={styles.body}>
          <HeaderText1 style={styles.welcome_text1}>
            {strings("start_screen.welcome-question")}
          </HeaderText1>

          <View style={styles.gender_choose}>
            {/* Male button */}
            <GenderButton
              gender={GENDERS.MALE}
              onPress={this._onMaleButtonPressed}
            />
            {/* Divider */}
            <View style={{ width: 10 }} />
            {/* Female button */}
            <GenderButton
              gender={GENDERS.FEMALE}
              onPress={this._onFemaleButtonPressed}
            />
          </View>

          {/* Login button */}
          <View style={styles.bottom_container}>
            <Button
              onPress={this._onLoginButtonPressed}
              title={strings("general.login")}
            />
          </View>
        </View>
      ]
    }));
  }

  _onMaleButtonPressed() {
    this._setGender(GENDERS.MALE);
  }

  _onFemaleButtonPressed() {
    this._setGender(GENDERS.FEMALE);
  }

  _setGender(gender) {
    this.setState({
      userGender: gender,
      setUpProgress: 1
    });
  }

  _onLoginButtonPressed() {}

  /* #endregion */

  /* #region Name Setup Page */

  _addNamePage() {
    console.log("Adding name page to ViewPager");

    this.setState(state => ({
      viewPagerItems: [
        ...state.viewPagerItems,
        <View key={"namePage"} style={styles.body}>
          {/* Page Title */}
          <HeaderText1>{strings("sign_up_wizard.set_name.title")}</HeaderText1>
          <Divider style={{ height: 20 }} />
          {/* Name Input */}
          <KeyboardAwareScrollView>
            <Input
              ref={userNameInput => {
                this._userNameInput = userNameInput;
              }}
              value={this.state.userName}
              textContentType="name"
              onChangeText={this._handeUserNameChange}
              containerStyle={styles.defaultInput}
              labelStyle={styles.inputWarning}
              placeholder={strings("sign_up_wizard.set_name.name_placeholder")}
              label={strings("sign_up_wizard.set_name.name_info")}
              maxLength={GlobalSettings.maxNameLength}
            />
          </KeyboardAwareScrollView>

          {/* Continue Button */}
          <View style={styles.bottom_container}>
            <Button
              onPress={this._onContinueNameSetup}
              title={strings("sign_up_wizard.continue_button")}
              disabled={!this.state.canContinueWithName}
            />
          </View>
        </View>
      ]
    }));
  }

  _setUserName(name) {}

  _onContinueNameSetup() {
    console.log("Continue button in name setup clicked!");
  }

  /* #endregion */

  /* #region Handle profile changes */

  _handeUserNameChange(name) {
    /* Check constraints */
    if (name.length < GlobalSettings.minNameLength) {
      console.log('Name: "' + name + '" to SHORT!');
      this.setState({
        canContinueWithName: false
      });

      console.log("Can continue with name:" + this.state.canContinueWithName);
      return;
    }

    if (name.length >= GlobalSettings.maxNameLength) {
      console.log('Name: "' + name + '" to LONG!');
      this.setState({
        canContinueWithName: false
      });

      console.log("Can continue with name:" + this.state.canContinueWithName);
      return;
    }

    /* Check successfull */

    console.log('Setting name to: "' + name + '" successfully!');

    // Save name + Make continue possible
    this.setState({
      canContinueWithName: true,
      userName: name,
      setUpProgress: 2
    });

    console.log("Can continue with name:" + this.state.canContinueWithName);
  }

  /* #endregion */

  /* #region Page scroll events */

  _onPageScroll(props) {
    // console.log(props);

    this.pagePosition = props.position;
    /*
    if (!this.expanded && props.offset > 0.5 && this.pagePosition == 0) {
      this._enableSetUpMode(true);
    }

    if (this.expanded && props.offset < 0.5 && props.position == 0) {
    this._enableSetUpMode(false);
    }*/
  }

  _onPageSelected(page) {
    console.log("Page Selected: " + page.position);

    if (page.position > 0) {
      this._enableSetUpMode(true);
    } else {
      this._enableSetUpMode(false);
    }
  }

  /* #endregion */

  _enableSetUpMode(enabled) {
    if (enabled == this.state.setUpMode) return;

    console.log("SetUp-Mode enabled: " + enabled);

    let animationDuration = 500;
    let maxHeight = 1;

    let fadeInLayoutAnimation = {
      duration: animationDuration,
      update: {
        type: LayoutAnimation.Types.easeIn
      }
    };

    let fadeOutLayoutAnimation = {
      duration: animationDuration,
      update: {
        type: LayoutAnimation.Types.easeOut
      }
    };

    if (enabled) {
      // Fade Opacity
      this._progressBarOpacityView.fadeIn(1, maxHeight, animationDuration);
      // this._progressBarOpacityView.fadeInAlpha(1, animationDuration);

      // Fade Height

      this.state.progressBarHeight.addListener(progress => {
        this.setState({ progressBarHeight_Value: progress.value });
      });

      Animated.timing(
        // Animate over time
        this.state.progressBarHeight, // The animated value to drive
        {
          toValue: maxHeight, // Animate to opacity: 1 (opaque)
          duration: animationDuration // Make it take a while
        }
      ).start(); // Starts the animation

      LayoutAnimation.configureNext(fadeInLayoutAnimation);

      this.setState({
        logoHeight: this.expandedLogoHeight,
        logoWidth: this.expandedLogoWidth
      });
    } else {
      // Fade Opacity
      this._progressBarOpacityView.fadeIn(0, 0, animationDuration);
      // this._progressBarOpacityView.fadeInAlpha(0, duration);

      // Fade Height

      this.state.progressBarHeight.addListener(progress => {
        this.setState({ progressBarHeight_Value: progress.value });
      });

      Animated.timing(
        // Animate over time
        this.state.progressBarHeight, // The animated value to drive
        {
          toValue: 0, // Animate to opacity: 1 (opaque)
          duration: animationDuration // Make it take a while
        }
      ).start(); // Starts the animation

      LayoutAnimation.configureNext(fadeOutLayoutAnimation);

      this.setState({
        logoHeight: this.defaultLogoHeight,
        logoWidth: this.defaultLogoWidth
      });
    }

    this.expanded = enabled;
  }

  render() {
    let { progressBarHeight_Value } = this.state;

    return (
      <ThemeProvider theme={Theme}>
        <View style={styles.root}>
          <GeneralStatusBarColor
            backgroundColor={colors.defaultButtonColor}
            barStyle="light-content"
          />

          <SafeAreaView style={{ flex: 1, backgroundColor: "#fff" }}>
            <View style={styles.align_center_X}>
              <Image
                style={{
                  width: this.state.logoWidth,
                  height: this.state.logoHeight,
                  resizeMode: "contain",
                  marginTop: hp("5%")
                }}
                source={Images.logoLandscape}
              />
            </View>

            {/* Setup progressbar */}
            <FadeInView
              ref={progressBarOpacityView => {
                this._progressBarOpacityView = progressBarOpacityView;
              }}
              style={styles.setUpProgressbar}
            >
              <ProgressBar
                ref={setUpProgressbar => {
                  this._setUpProgressbar = setUpProgressbar;
                }}
                progress={0.6}
                width={null}
                color={colors.defaultButtonColor}
              />
            </FadeInView>

            <ViewPager
              ref={viewPager => {
                this._viewPager = viewPager;
              }}
              style={styles.pageWrapper}
              onPageScroll={this._onPageScroll}
              onPageSelected={this._onPageSelected}
            >
              {this.state.viewPagerItems}
            </ViewPager>
          </SafeAreaView>
        </View>
      </ThemeProvider>
    );
  }
}

const styles = StyleSheet.create({
  root: {
    backgroundColor: "white",
    flex: 1
  },

  align_center_X: {
    alignItems: "center"
  },

  gender_choose: {
    marginTop: 30,

    flexDirection: "row",
    justifyContent: "space-between"
  },

  defaultInput: {
    width: 300
  },

  inputWarning: {
    fontSize: 10
  },

  setUpProgressbar: {
    marginLeft: 50,
    marginRight: 50,
    marginTop: 5,
    height: 6
  },

  pageWrapper: {
    flex: 1,
    marginTop: hp("5%")
  },

  body: {
    flex: 1,
    alignItems: "center"
  },

  bottom_container: {
    position: "absolute",
    bottom: hp("5%")
  }
});


0 个答案:

没有答案