我对整个React Native和JS都是新手,所以我可能在这里犯了一个愚蠢的错误。我有从这里得到的以下代码:https://reactnativecode.com/change-image-source-dynamically/
我希望循环代码进行了一些调整。
问题如下:第一次更改。然后,再次单击它会更改URL(就像在Text组件中一样),但是图像不会再次显示。然后,再次按下(第三次),“文本”(变量名)将不再更改,并且图像仍不会显示。
import React, { Component } from 'react';
import { StyleSheet, View, Text, Image, Button, Platform, TouchableHighlight } from 'react-native';
export default class App extends Component {
constructor() {
super();
this.state = {
imageURL: 'https://reactnativecode.com/wp-content/uploads/2017/10/Guitar.jpg'
}
}
Load_New_Image = () => {
if (this.state.imageURL == 'https://reactnativecode.com/wp-content/uploads/2017/10/Guitar.jpg'){
this.setState({
imageURL: 'https://reactnativecode.com/wp-content/uploads/2018/02/motorcycle.jpg'
})
}else{
this.setState({
imageURL: 'https://reactnativecode.com/wp-content/uploads/2018/02/Guitar.jpg'
})
}
}
render() {
console.log('source: ', this.state.imageURL)
return (
<View style={styles.MainContainer}>
<TouchableHighlight onPress={this.Load_New_Image}>
<Image
key={this.state.imageURL}
source={{ uri: this.state.imageURL }}
style={styles.imageStyle} />
</TouchableHighlight>
<Text>{this.state.imageURL}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
margin: 10
},
imageStyle: {
width: 200,
height: 300,
resizeMode: 'center'
}
});