单击按钮时反应本机更改图像源

React Native chagne image source on button click

您好,我正在尝试通过单击按钮更改图像,但似乎无法更改图像。这是我的代码。

constructor(){
   super()
   this.state = {
      autologin_active: true
   }
}

toggleAutoLogin(){
   this.state.autologin_active = this.state.autologin_active ? false : true;
}


<TouchableHighlight onPress={() => this.toggleAutoLogin()} style={styles.registerButton} underlayColor='#99d9f4'>
  <View style={styles.detailBoxTick}>
    <Image style={styles.imageTickStyle} source={this.state.autologin_active ? Images.rememberTickImg : Images.rememberUnTickImg} />
    <Text style={styles.tickBoxText}>
      Auto Login
    </Text>
  </View>          
</TouchableHighlight>

有人可以帮忙吗?不确定我做错了什么。已通过警报检查状态是否在单击时发生变化。提前致谢

如果我没听错,在 toggleAutoLogin() 中,您正在使用 this.state.autologin_active = ..... 更新状态,这会更新状态但会阻止重新渲染,这样您就看不到图像发生变化.

您需要使用 setState({}) 更新状态才能重新渲染组件 (Image)。

您的 toggleAutoLogin() 代码将是:

this.setState({ autologin_active: this.state.autologin_active ? false : true})