我想根据传递的道具渲染图像。首先注释掉的filePath是源。我已经尝试了几种变体,但是它总是给我同样的错误。react文档并没有真正涵盖您在30多种不同场景下的处理方法。我可以向该组件添加状态,并使其包含所有文件变体,但这似乎比必要的工作还要多。 https://facebook.github.io/react-native/docs/images
class Weather extends React.Component {
render() {
// let filePath = "./weatherimg/01d.png";
let filePath = `./weatherimg/${this.props.icon.icon}.png`;
let filePath2 = this.props.icon ? require(filePath) : require(filePath);
return (
<View >
<Text>{this.props.location} {this.props.data[0]}</Text>
<Text>{this.props.data[1]}</Text>
<Text>Low {this.props.temps.low}, High {this.props.temps.high}</Text>
<Text>{this.props.icon.description}</Text>
<View style={{width: 60, height: 60}}>
<Image source={filePath2} style={{flex: 1}} />
</View>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud) 它告诉我 this.setState' 是未定义的,但我不确定我能做些什么来使“this”指向 setState 的正确上下文。我不知道我还能绑定什么来帮助。
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import axios from 'react-native-axios';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 50
}
this.apirequest = this.apirequest.bind(this);
}
componentWillMount() {
this.apirequest();
}
apirequest() {
axios.get('http://api.openweathermap.org/data/2.5/weather')
.then(function (response) {
console.log(response.data.main.temp);
this.setState({
data: response.data.main.temp
})
})
.catch(function (error) {
console.log(error);
});
}
Run Code Online (Sandbox Code Playgroud)