单击时更改图像背景

Changing ImageBackground onClick

我有一个带有图像背景的视图。在此之下,我有 3 个按钮。我想要这样,当您单击其中一个按钮时,图像背景会发生变化。

我想每次都使用 switch case 来改变状态,但它不起作用。我有点迷路了...我 post 我的代码,如果您有任何想法,非常感谢您的帮助!

    export default class Weight extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          bgWidth: "100%",
          bgHeight: 0,
          animalBg:'duck',
          stats: {
            total_weight_carried: 0,
          },
        };
      }
    
      setBackgroundDimensions = (real_width, real_height) => {
        let final_width = real_width;
        let final_height = real_height * (width * 100 / real_width) / 100;
    
        this.setState({
          bgWidth: "100%", // Force 100% for compatibility
          bgHeight: final_height
        });
    
        console.log(height, real_height, (width * 100 / real_width), final_height);
      };
    
      UNSAFE_componentWillMount() {
        // Image.getSize(bgStatsURL, (width, height) => {this.setBackgroundDimensions({width, height})});
        this.setBackgroundDimensions(1125, 1589);
      }
    
   duck = () => {
    return(
      <ImageBackground
      source={require('../../assets/images/stats/bg-stats-weight-duck.jpg')}
      style={{ flex: 1, width: this.state.bgWidth, height: this.state.bgHeight, marginVertical: 25}}
      imageStyle={{ resizeMode: "contain" }}
    >
      <View style={{zIndex: 1, flexDirection: "row", justifyContent: 'center', marginTop: 5}}>
        <Text style={styles.statText}>
          <AnimateNumber
            value={this.state.stats.total_weight_carried}
            countBy={(this.state.stats.total_weight_carried / 50).toFixed(0)}
            style={styles.statTextData}
          />{" "}
          {i18n.t("stats.unit.kg")}
        </Text>
      </View>
      <View style={[styles.row, { marginTop: 450, alignItems: 'center', justifyContent: 'center'}]}>
        <Text style={styles.statText}>x ducks</Text>
      </View>
    </ImageBackground>
    )
  }

  elephant = () => {
    return(
    <ImageBackground
      source={require('../../assets/images/stats/bg-stats-weight-elephant.jpg')}
      style={{ flex: 1, width: this.state.bgWidth, height: this.state.bgHeight, marginVertical: 25}}
      imageStyle={{ resizeMode: "contain" }}
    >
      <View style={{zIndex: 1, flexDirection: "row", justifyContent: 'center', marginTop: 5}}>
        <Text style={styles.statText}>
          <AnimateNumber
            value={this.state.stats.total_weight_carried}
            countBy={(this.state.stats.total_weight_carried / 50).toFixed(0)}
            style={styles.statTextData}
          />{" "}
          {i18n.t("stats.unit.kg")}
        </Text>
      </View>
      <View style={[styles.row, { marginTop: 450, alignItems: 'center', justifyContent: 'center'}]}>
        <Text style={styles.statText}>x ducks</Text>
      </View>
    </ImageBackground>
    )
  }

  trex = () => {
    return(
      <ImageBackground
      source={require('../../assets/images/stats/bg-stats-weight-trex.jpg')}
      style={{ flex: 1, width: this.state.bgWidth, height: this.state.bgHeight, marginVertical: 25}}
      imageStyle={{ resizeMode: "contain" }}
    >
      <View style={{zIndex: 1, flexDirection: "row", justifyContent: 'center', marginTop: 5}}>
        <Text style={styles.statText}>
          <AnimateNumber
            value={this.state.stats.total_weight_carried}
            countBy={(this.state.stats.total_weight_carried / 50).toFixed(0)}
            style={styles.statTextData}
          />{" "}
          {i18n.t("stats.unit.kg")}
        </Text>
      </View>
      <View style={[styles.row, { marginTop: 450, alignItems: 'center', justifyContent: 'center'}]}>
        <Text style={styles.statText}>x ducks</Text>
      </View>
    </ImageBackground>
    )
  };

      choiceAction = (val) => {
        switch(val) {
          case "duck":
            this.duck();
          break;
          case "elephant":
            this.elephant();
          break;
          case "trex":
            this.trex();
          break;
          default:
            this.duck();
        }
      };
    
      render() {
        return (
          <ScrollView style={styles.containerScrollNoMargins}>
            <ImageBackground
              source={require("../../assets/images/background-stats.jpg")}
              style={{ flex: 1 }}
              imageStyle={{ resizeMode: "stretch" }}
            >
              <SafeAreaView>
                <View style={styles.rankingContainer}>
                  <Image
                    source={require("../../assets/images/cadran.png")}
                    style={styles.btnRanking}
                  />
                  <View style={[styles.row, { marginTop: 28, marginLeft: 55}]}>
                    <Text style={styles.statText}>{i18n.t("stats.action.weight")}</Text>
                  </View>
                  <Text
                    style={[styles.textimg, styles.measure]}
                    onLayout={this.handleLayout}
                  >
                    0
                  </Text>
                  <Image
                    source={require("../../assets/images/btn-header-background.png")}
                    style={styles.cadran}
                  />
                </View>
              </SafeAreaView>
              {this.choiceAction()}
              <View style={{flexDirection:'row', alignItems: 'center', justifyContent: 'space-around'}}>
                <TouchableOpacity
                  style={styles.zoom}
                  onPress={() => this.props.navigation.navigate("FlightsList")}
                >
                  <Image
                    source={require("../../assets/images/stats/btn-canard.png")}
                    style={styles.weightImg}
                  />
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.zoom}
                  onPress={this.choiceAction('duck')}
                >
                  <Image
                    source={require("../../assets/images/stats/btn-elephant.png")}
                    style={styles.weightImg}
                  />
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.zoom}
                  onPress={this.choiceAction('elephant')}
                >
                  <Image
                    source={require("../../assets/images/stats/btn-trex.png")}
                    style={styles.weightImg}
                  />
                </TouchableOpacity>
              </View>
              <View style={styles.subContainer}>
                <TouchableOpacity
                  style={styles.touchable2}
                  onPress={this.choiceAction('trex')}
                >
                  <View style={styles.view2}>
                    <Text style={styles.textimg2}>
                      {i18n.t("signup.action.back")}
                    </Text>
                  </View>
                  <Image
                    source={require("../../assets/images/btn-background.png")}
                    style={styles.tripsimg2}
                  />
                </TouchableOpacity>
              </View>
            </ImageBackground>
          </ScrollView>
        );
      }
    }

我已经更新了代码。你做错了几件事。

第一个

onPress={this.choiceAction('duck')}

onPress 需要一个函数,但是您执行此操作的方式将在组件呈现后立即执行该函数。正确的做法是

onPress={()=>this.choiceAction('duck')}

第二

choiceAction = (val) => {
        switch(val) {
          case "duck":
            this.duck();
          break;
          case "elephant":
            this.elephant();
          break;
          case "trex":
            this.trex();
          break;
          default:
            this.duck();
        }
      };

这个函数不会 return 任何东西。它肯定会基于 switch-case 执行其他功能,但它不会 return 任何东西。

我更新了代码,对函数名做了一些调整。看一看,如果这对你有效,请告诉我。

export default class Weight extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bgWidth: "100%",
            bgHeight: 0,
            animalBg: 'duck',
            stats: {
                total_weight_carried: 0,
            },
            choice: ''
        };
    }

    setBackgroundDimensions = (real_width, real_height) => {
        let final_width = real_width;
        let final_height = real_height * (width * 100 / real_width) / 100;

        this.setState({
            bgWidth: "100%", // Force 100% for compatibility
            bgHeight: final_height
        });

        console.log(height, real_height, (width * 100 / real_width), final_height);
    };

    UNSAFE_componentWillMount() {
        // Image.getSize(bgStatsURL, (width, height) => {this.setBackgroundDimensions({width, height})});
        this.setBackgroundDimensions(1125, 1589);
    }

    duck = () => {
        return (
            <ImageBackground
                source={require('../../assets/images/stats/bg-stats-weight-duck.jpg')}
                style={{ flex: 1, width: this.state.bgWidth, height: this.state.bgHeight, marginVertical: 25 }}
                imageStyle={{ resizeMode: "contain" }}
            >
                <View style={{ zIndex: 1, flexDirection: "row", justifyContent: 'center', marginTop: 5 }}>
                    <Text style={styles.statText}>
                        <AnimateNumber
                            value={this.state.stats.total_weight_carried}
                            countBy={(this.state.stats.total_weight_carried / 50).toFixed(0)}
                            style={styles.statTextData}
                        />{" "}
                        {i18n.t("stats.unit.kg")}
                    </Text>
                </View>
                <View style={[styles.row, { marginTop: 450, alignItems: 'center', justifyContent: 'center' }]}>
                    <Text style={styles.statText}>x ducks</Text>
                </View>
            </ImageBackground>
        )
    }

    elephant = () => {
        return (
            <ImageBackground
                source={require('../../assets/images/stats/bg-stats-weight-elephant.jpg')}
                style={{ flex: 1, width: this.state.bgWidth, height: this.state.bgHeight, marginVertical: 25 }}
                imageStyle={{ resizeMode: "contain" }}
            >
                <View style={{ zIndex: 1, flexDirection: "row", justifyContent: 'center', marginTop: 5 }}>
                    <Text style={styles.statText}>
                        <AnimateNumber
                            value={this.state.stats.total_weight_carried}
                            countBy={(this.state.stats.total_weight_carried / 50).toFixed(0)}
                            style={styles.statTextData}
                        />{" "}
                        {i18n.t("stats.unit.kg")}
                    </Text>
                </View>
                <View style={[styles.row, { marginTop: 450, alignItems: 'center', justifyContent: 'center' }]}>
                    <Text style={styles.statText}>x ducks</Text>
                </View>
            </ImageBackground>
        )
    }

    trex = () => {
        return (
            <ImageBackground
                source={require('../../assets/images/stats/bg-stats-weight-trex.jpg')}
                style={{ flex: 1, width: this.state.bgWidth, height: this.state.bgHeight, marginVertical: 25 }}
                imageStyle={{ resizeMode: "contain" }}
            >
                <View style={{ zIndex: 1, flexDirection: "row", justifyContent: 'center', marginTop: 5 }}>
                    <Text style={styles.statText}>
                        <AnimateNumber
                            value={this.state.stats.total_weight_carried}
                            countBy={(this.state.stats.total_weight_carried / 50).toFixed(0)}
                            style={styles.statTextData}
                        />{" "}
                        {i18n.t("stats.unit.kg")}
                    </Text>
                </View>
                <View style={[styles.row, { marginTop: 450, alignItems: 'center', justifyContent: 'center' }]}>
                    <Text style={styles.statText}>x ducks</Text>
                </View>
            </ImageBackground>
        )
    };
    setChoiceAction = (choice) => this.setState({ choice })
    getChoiceAction = () => {
        switch (this.state.choice) {
            case "duck":
                return this.duck();
            case "elephant":
                return this.elephant();
            case "trex":
                return this.trex();
            default:
                this.duck();
        }
    };

    render() {
        return (
            <ScrollView style={styles.containerScrollNoMargins}>
                <ImageBackground
                    source={require("../../assets/images/background-stats.jpg")}
                    style={{ flex: 1 }}
                    imageStyle={{ resizeMode: "stretch" }}
                >
                    <SafeAreaView>
                        <View style={styles.rankingContainer}>
                            <Image
                                source={require("../../assets/images/cadran.png")}
                                style={styles.btnRanking}
                            />
                            <View style={[styles.row, { marginTop: 28, marginLeft: 55 }]}>
                                <Text style={styles.statText}>{i18n.t("stats.action.weight")}</Text>
                            </View>
                            <Text
                                style={[styles.textimg, styles.measure]}
                                onLayout={this.handleLayout}
                            >
                                0
                  </Text>
                            <Image
                                source={require("../../assets/images/btn-header-background.png")}
                                style={styles.cadran}
                            />
                        </View>
                    </SafeAreaView>
                    {this.getChoiceAction()}
                    <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around' }}>
                        <TouchableOpacity
                            style={styles.zoom}
                            onPress={() => this.props.navigation.navigate("FlightsList")}
                        >
                            <Image
                                source={require("../../assets/images/stats/btn-canard.png")}
                                style={styles.weightImg}
                            />
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={styles.zoom}
                            onPress={() => this.setChoiceAction('duck')}
                        >
                            <Image
                                source={require("../../assets/images/stats/btn-elephant.png")}
                                style={styles.weightImg}
                            />
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={styles.zoom}
                            onPress={() => this.setChoiceAction('elephant')}
                        >
                            <Image
                                source={require("../../assets/images/stats/btn-trex.png")}
                                style={styles.weightImg}
                            />
                        </TouchableOpacity>
                    </View>
                    <View style={styles.subContainer}>
                        <TouchableOpacity
                            style={styles.touchable2}
                            onPress={() => this.setChoiceAction('trex')}
                        >
                            <View style={styles.view2}>
                                <Text style={styles.textimg2}>
                                    {i18n.t("signup.action.back")}
                                </Text>
                            </View>
                            <Image
                                source={require("../../assets/images/btn-background.png")}
                                style={styles.tripsimg2}
                            />
                        </TouchableOpacity>
                    </View>
                </ImageBackground>
            </ScrollView>
        );
    }
}