我是一个反应原住民的初学者,正在开发一个应用程序,从我的API中获取文本和图像,并在屏幕上显示它。显示文本,但不显示图像。没有错误。我只有一个主文件: API调用为App.js
https://www.teanewsnetwork.com/api/fetcharticles.php?code=Me*z6Pcw9e1$CQ)YWgMlFe%nv(Hq)lhw&starting=0&limit=20 App.js:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, { Component } from 'react';
import {
View,
Text,
ActivityIndicator,
ScrollView,
StyleSheet,
Image,
} from 'react-native';
import Img from 'react-image';
let li = 'https://www.teanewsnetwork.com/profileicons/';
let bean = 'azure.jpg';
export default class App extends Component {
state = {
loading: true,
error: false,
posts: [],
};
componentWillMount = async () => {
try {
const response = await fetch(
'https://www.teanewsnetwork.com/api/fetcharticles.php?code=Me*z6Pcw9e1$CQ)YWgMlFe%nv(Hq)lhw&starting=0&limit=40'
);
const posts = await response.json();
this.setState({ loading: false, posts });
} catch (e) {
this.setState({ loading: false, error: true });
}
};
renderPost = ({ id, title, content, authorimage, authorname }, i) => {
let b = { authorname };
return (
<View style={styles.postContent}>
<Text>{authorname}</Text>
<Image
source={{
uri: 'https://teanewsnetwork.com/profileicons/',
}}
style={{ width: 40, height: 40 }}
/>
<Text style={styles.postauthor}>{title}</Text>
<Text style={styles.postBody}>{content}</Text>
</View>
);
};
render() {
const { posts, loading, error } = this.state;
if (loading) {
return (
<View style={styles.center}>
<ActivityIndicator animating={true} />
</View>
);
}
if (error) {
return (
<View style={styles.center}>
<Text>Failed to load posts!</Text>
</View>
);
}
return (
<ScrollView style={styles.container}>
{posts.map(this.renderPost)}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
postauthor: {
flex: 1,
borderBottomWidth: 1,
borderBottomColor: '#EEE',
paddingVertical: 25,
paddingRight: 15,
},
postContent: {
flex: 1,
borderBottomWidth: 1,
borderBottomColor: '#EEE',
paddingVertical: 25,
paddingRight: 15,
left: 10,
},
postBody: {
marginTop: 10,
fontSize: 12,
color: 'lightgray',
left: 10,
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});我想在链接的每个名字下面显示我的图片
www.teanewsnetwork.com/profileicons/{{authorimage}}其中{{authorimage}}是在API中给出的。但这似乎行不通。谢谢你提前了!
发布于 2018-11-29 14:00:34
您可以在模板文字中使用JavaScript。这将把authtorimage追加到字符串的末尾。
<Image
source={{
uri: `https://teanewsnetwork.com/profileicons/${authorimage}`,
}}
style={{ width: 40, height: 40 }}/>模板文字用反勾(`) (严肃重音)字符括起来,而不是双引号或单引号。模板文字可以包含占位符。这些都是由美元符号和大括号(${expression})表示的。占位符中的表达式及其之间的文本被传递给函数。
发布于 2018-11-29 14:23:09
你这样做是非常正确的,除了我在下面指出的两处:
import Img from 'react-image';这是不必要的,因为react本机本身提供了Image组件。
<Image
source= {{
uri: `https://teanewsnetwork.com/profileicons/${authorimage}`,
}}
style={{height: 40, width: 40}}
/>https://stackoverflow.com/questions/53540657
复制相似问题