我要在提交城市名称时更改背景图像,但不知道如何动态更改背景图像。.我一直在使用三元运算符,但没有提供所需的输出。(原生noobie)
这是我的主要代码。
import React, {Component} from 'react';
import {Image, TextInput, ImageBackground, StyleSheet, Text, View} from 'react-native';
import OpenWeatherMap from './Components/openweathermap';
import WeatherForecast from './Components/forecast';
import Images from './android/app/assets/images';
export default class why extends Component {
constructor(props){
super(props);
this.state = {forecast: null, doesShow: false};
}
textHandleChange = event => {
let city = event.nativeEvent.text;
OpenWeatherMap.fetchWeather(city).then(forecast =>{
this.setState({forecast : forecast}); //Used for fetching weather data using fetchAPI
});
}
backgroundChange = () => {
this.setState({doesShow:true})
}
render(){
let content = null;
if(this.state.forecast !== null){
content = (
<WeatherForecast
main = {this.state.forecast.main}
description = {this.state.forecast.description}
temp = {this.state.forecast.temp} //For displaying the fetched Weather data
/>
);
}
return(
{ {this.state.doesShow} === true ?
<ImageBackground
source = {Images.pic4}
style={styles.imageDeco}> :
<ImageBackground
source = {Images.pic3}
style={styles.imageDeco}> }
<View style= {styles.a1}>
<View style = {styles.top}>
<Text style={styles.a2}>Weather Forecast</Text>
</View>
<Text style={styles.a3}>Enter your city ID</Text>
<TextInput
onSubmitEditing={this.textHandleChange}
onChangeText={this.backgroundChange}
style={styles.a4}></TextInput>
{content}
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
imageDeco:{
flex:1,
width: '100%',
height: '100%'
},
a1:{
flex:1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(47,163,218,0.2)'
},
a2:{
fontSize: 30,
color: 'rgba(128,0,0,1)',
borderColor: '#FFF',
borderWidth: 2,
backgroundColor: 'rgba(255,219,153,0.6)',
padding: 10,
paddingLeft: 10,
paddingRight: 10,
fontFamily: 'Lobster'
},
a3:{
fontSize: 25,
color: 'blue',
fontFamily: 'Pacifico'
},
a4:{
backgroundColor:'#ffe0bd',
width: '30%',
marginTop: 20,
borderColor: 'black',
borderRadius: 50,
fontFamily: 'Lobster',
fontSize: 30,
},
top:{
justifyContent:'center',
alignItems:'center',
width: '70%'
}
})
我的主要目的是从获取的天气数据中更改背景图像。
答案 0 :(得分:1)
var icon = this.props.img1 ? require('image/img1.png') : require('image/img2.png');
<Image source={icon} />
您可以使用switch
在此处根据需要更改逻辑,也可以根据需要构建require ..
并通过嵌套形式react-native使用背景img。我一直都这样做。您可以在此处找到详细信息:https://facebook.github.io/react-native/docs/images#background-image-via-nesting