更改ImageBackground onClick

如何解决更改ImageBackground onClick

我有一个imagebackground的视图。在此之下,我有3个按钮。我想要的是,当您单击其中一个按钮时,imagebackground会更改。

我想每次都使用带有状态变化的开关盒,但这没有用。我有点迷路了...我发布了代码,如果您有任何想法,非常感谢您的帮助!

    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,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,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',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();
        }
      };

此函数不会返回任何内容。它肯定会基于switch-case执行其他功能,但不会返回任何内容。

我已经更新了代码,并且几乎没有对函数名称进行任何调整。看一看,让我知道这是否可以解决您的问题。

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,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,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',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>
        );
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?