您可以通过以下步骤做到这一点:
第 1 步:使用以下命令在当前项目上安装 "react-native-link-preview" 包:
yarn add react-native-link-preview
第 2 步:这是您可以获取链接详细信息的代码:如链接标题、链接缩略图等。
LinkPreview.getPreview('https://www.youtube.com/watch?v=MejbOFk7H6c')
.then(data => console.debug(data));
完整代码:
import React, { Component } from 'react';
import { Text, View, FlatList, Image } from 'react-native';
import LinkPreview from 'react-native-link-preview';
let links = [
{
link: 'https://aws.amazon.com/'
},
{
link: 'https://firebase.google.com/'
},
{
link: 'https://www.youtube.com/watch?v=Kmiw4FYTg2U'
},
{
link: 'https://en.wikipedia.org/wiki/React_Native'
},
{
link:'https://stackoverflow.com/'
}
];
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
linkData: []
};
}
async componentDidMount() {
let _tempLinkData = [];
for (let link of links) {
await LinkPreview.getPreview(link.link)
.then(data => {
console.debug("Data : ", data);
let _newLinkDetails = {
link: link.link,
title: data.title,
thumbnail: data.images[0]
};
_tempLinkData.push(_newLinkDetails);
});
}
this.setState({ linkData: _tempLinkData });
}
render() {
return (
<View style={{ marginTop: 35 }}>
<FlatList
contentContainerStyle={{ paddingHorizontal: 20}}
data={this.state.linkData}
renderItem={({ item }) => (
<View style={{ flex: 1, flexDirection: "row", padding: 5 }}>
<Image
style={{ width: 50, height: 50 }}
source={{ uri: item.thumbnail }}
/>
<View style={{ marginLeft: 10, }}>
<Text style={{ fontSize: 16, lineHeight: 20, }}>{item.title}</Text>
<View style={{ flex: 1, flexDirection: "row", justifyContent: "space-between", }}>
<Text style={{ fontSize: 16, lineHeight: 20, color: "#a1a1a1" }}>{item.link}</Text>
</View>
</View>
</View>
)}
keyExtractor={(item, index) => String(index)}
/>
</View>
);
}
}