Monday, May 20, 2024
117
rated 0 times [  122] [ 5]  / answers: 1 / hits: 24480  / 7 Years ago, sat, june 17, 2017, 12:00:00

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.



Simplified code is below:



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

More From » react-native

 Answers
11

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

[#57413] Thursday, June 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aden

Total Points: 369
Total Questions: 100
Total Answers: 83

Location: Australia
Member since Tue, Oct 19, 2021
3 Years ago
;