2017-06-17 55 views
0

我目前有一个图像包装在一个TouchableOpacity标签内。图像是一个声音图标,当用户点击它时,我希望图标在“声音开启”图标和“声音关闭”图标之间切换。相关的代码可以在下面看到。我并不担心它的切换部分,我只是想在点击它时切换图像。更改反应原生图像源点击

简化代码如下:

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

将图像源存储在状态中,并在按下按钮时用新图像源执行setState()。这将重新渲染组件,您可以从状态设置新的图像。 –

回答

2

标签是JSX语法,所以你不能编辑它的属性(点)的语法。以下是正确的方法。

const soundImg = require('../images/sound.png'); 
const muteImg = require('../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 }) } 
      /> 
      {thi.renderImage()} 
      </TouchableOpacity> 
     </View> 
     </View> 
    ); 
    } 
} 
+0

谢谢!完美的作品。我对React仍然很陌生,但这样做更有意义。 – OstrichGlue