Change React Native Image source on click

后端 未结 2 1848
闹比i
闹比i 2021-01-03 07:03

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 \"

相关标签:
2条回答
  • 2021-01-03 07:21

    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>
        );
      }
    }
    
    0 讨论(0)
  • 2021-01-03 07:27

    I'm using the following way and its working fine.

    class HomeScreen extends Component {
      static navigationOptions = {
        header: null,
    };
    
    constructor() {
        super();
    
        this.state = {
          flagImage:true
        };
    }
    
    render(){
        let imageXml = <Image
          style={ homeStyles.optionsImage }
          source={ gearImg }
        />;
        return (
          <View style={ commonStyles.container }>
            <View style={ commonStyles.footer }>
              <TouchableOpacity
                style={ homeStyles.soundButton }
                onPress={ this.changeImage }>
    
              <Image source={ this.state.flagImage === true ?                  
                              require('../images/sound.png') : 
                              require('../images/sound-mute.png')}
               />
    
              </TouchableOpacity>
            </View>
          </View>
        );
      }
    }
    
    changeImage() {
    
       this.setState({
          flagImage:!this.state.flagImage
        });
    
    }
    
    0 讨论(0)
提交回复
热议问题