单击更改React Native Image源 [英] Change React Native Image source on click

查看:63
本文介绍了单击更改React Native Image源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在TouchableOpacity标签内部包含一个Image。图像是声音图标,当用户点击它时,我希望图标在声音开启图标和声音关闭图标之间切换。相关代码如下所示。我并不担心它的切换部分,我只是希望能够在点击它时切换图像。

I currently have an Image wrapped inside of a TouchableOpacity tag. The image is of a sound icon, and when the user clicks it, I would like the icon to switch between the "sound on" icon and the "sound off" icon. The relevant code can be seen below. I'm not worrying about the toggle portion of it yet, I just would like to be able to switch the image when tapping it.

简化代码如下:

const soundImg = require('../images/sound.png');
const muteImg = require('../images/sound-mute.png');

class HomeScreen extends Component {
  static navigationOptions = {
    header: null,
  };
  render(){
    let imageXml = <Image
      style={ homeStyles.optionsImage }
      source={ gearImg }
    />;
    return (
      <View style={ commonStyles.container }>
        <View style={ commonStyles.footer }>
          <TouchableOpacity
            style={ homeStyles.soundButton }
            onPress={ () => imageXml.source = { muteImg } }>
            { imageXml }
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}


推荐答案

标签是JSX语法,因此您无法通过。(点)语法编辑其属性。以下是正确的方法。

Tag is JSX Syntax so you cannot edit its property by .(dot) syntax. Following is the correct way to do it.

import soundImg from '../images/sound.png';
import muteImg from '../images/sound-mute.png';

class HomeScreen extends Component {
  constructor() {
    super();
    this.state = { showSoundImg: true };
  }
  static navigationOptions = {
    header: null,
  };
  renderImage() = {
    var imgSource = this.state.showSoundImg? soundImg : muteImg;
    return (
      <Image
        style={ homeStyles.optionsImage }
        source={ imgSource }
      />
    );
  }
  render(){
    return (
      <View style={ commonStyles.container }>
        <View style={ commonStyles.footer }>
          <TouchableOpacity
            style={ homeStyles.soundButton }
            onPress={ () => this.setState({ showSoundImg: !this.state.showSoundImg }) } 
          />
            {this.renderImage()}
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

这篇关于单击更改React Native Image源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆