如何使用React Native构建新闻应用

金高轩
2023-12-01

by Mohammed Salman

穆罕默德·萨尔曼(Mohammed Salman)

如何使用React Native构建新闻应用 (How to build a news app with React Native)

For my first post on Medium, and I wanted to share with you how I made a news app with React Native.

对于我在Medium上的第一篇文章,我想与大家分享我如何使用React Native制作新闻应用程序。

Originally posted on my blog.

最初发布在我的博客上。

Requirements for building the app:

构建应用程序的要求:

If you’re not familiar with these resources, don’t worry — they are quite easy to use.

如果您不熟悉这些资源,请不用担心-它们非常易于使用。

The topics we will cover in the post are:

我们将在帖子中介绍的主题是:

  • News API

    新闻API
  • Fetch API

    提取API
  • FlatList

    平面清单
  • Pull down to refresh

    下拉刷新
  • Linking

    连结中

And more…so let’s get started!

还有更多……让我们开始吧!

You can find the project repo here

你可以在这里找到项目仓库

新闻API (News API)

A simple and easy-to-use API that returns JSON metadata for headlines and articles live all over the web right now. — NewsAPI.org

一个简单易用的API可以立即返回标题和文章的JSON元数据,并且可以在整个Web上实时播放。 NewsAPI.org

First, you should go ahead and sign up for News Api to get your free apiKey (your authentication key).

首先,您应该继续并注册News Api以获取免费的apiKey ( 您的身份验证密钥 )。

Create a new React Native project, and call it news_app (or whatever you want). In the project directory, make a new folder and call it src . In the src directory, create a folder an name it components . So your project directory should look something like this:

创建一个新的React Native项目,并将其news_app (或任何您想要的名称)。 在项目目录中,新建一个文件夹,并将其命名为src 。 在src目录中,创建一个名称为components的文件夹。 因此,您的项目目录应如下所示:

In the src folder, create a new file called news.js . In this file we are going to fetch the JSON that contains the headlines from the News API.

src文件夹中,创建一个名为news.js的新文件。 在此文件中,我们将从News API中获取包含标题的JSON。

news.js (news.js)

Make sure you replace YOUR_API_KEY_HERE with your own API key. For more information about the News API, go to newsapi docs.

确保使用您自己的API密钥替换YOUR_API_KEY_HERE。 有关News API的更多信息,请访问 newsapi docs

Now we declare the getNews function, which is going to fetch the articles for us. Export the function so we can use it in our App.js file.

现在,我们声明getNews函数,它将为我们获取文章。 导出函数,以便我们可以在App.js文件中使用它。

App.js (App.js)

In the constructor, we define the initial state. articles will store our articles after we fetch them, and refreshing will help us in refresh animation. Notice that I set the refreshing bool to true, because when we start the app, we want the animation to start while we load the articles (news headlines).

在构造函数中,我们定义初始状态。 articles将在我们提取之后存储我们的文章,而refreshing将有助于我们刷新动画。 请注意,我将refreshing布尔值设置为true,因为在启动应用程序时, 我们希望动画在加载文章 (新闻标题)时开始。

componentDidMount is invoked immediately after a component is mounted. Inside it we call the fetchNews method.

componentDidMount一个部件被安装之后被立即调用。 在其中,我们称为fetchNews方法。

componentDidMount() {  this.fetchNews();}

In fetchNews we call getNews() which returns a promise. So we use the .then() method which takes a callback function, and the callback function takes an argument (the articles).

fetchNews我们调用getNews()返回一个promise 。 因此,我们使用.then()方法,该方法带有一个回调函数,而该回调函数带有一个参数( articles )。

Now assign the articles in the state to the articles argument. I only typed articles because it’s a new ES6 syntax which means { articles: articles } , and we set refreshing to false to stop the spinner animation.

现在,将状态中的文章分配给articles参数。 我仅输入articles是因为它是一种新的ES6语法,这意味着{ articles: articles } article { articles: articles } ,并且我们将refreshing设置为false以停止微调器动画。

fetchNews() {  getNews().then(      articles => this.setState({ articles, refreshing: false })  ).catch(() => this.setState({ refreshing: false }));}

.catch() is called in rejected cases.

.catch() 在拒绝的情况下被调用。

handleRefresh method is going to start the spinner animation and call the fetchNews() method. We pass () => this.fetchNews() , so it’s called immediately after we assign the state.

handleRefresh方法将启动微调器动画并调用fetchNews()方法。 我们通过() => this.fetchNew s(),因此在分配状态后立即调用它。

handleRefresh() {  this.setState({ refreshing: true },() => this.fetchNews());}

Inside the render method, we return a FlatList component. Then we pass some props. data is the array of articles from this.state . The renderItem takes a function to render each item in the array, but in our case it just returns the Article component we imported earlier (we’ll get to it). And we pass the article item as a prop to use later in that component.

在render方法内部,我们返回一个FlatList组件。 然后我们传递一些道具。 datathis.state的文章数组。 renderItem一个函数来渲染数组中的每个项目,但是在我们的例子中,它只是返回我们之前导入的Article组件(我们将介绍它)。 我们将文章项作为道具传递给以后在该组件中使用。

Article.js (Article.js)

In src/components create a new JavaScript file and call it Article.js

src / components中创建一个新JavaScript文件,并将其命名为Article.js

Let’s start by installing two simple libraries using npm: react-native-elements, which gives us some premade components we could use, and moment that will handle our time.

让我们开始使用npm安装两个简单的库: react-native-elements ,这给了我们一些预制的 组件,我们可以使用,并时刻将处理我们的时间。

Install them using npm:

使用npm安装它们:

npm install --save react-native-elements moment

In Article.js:

在Article.js中:

There is a lot going on here. First, we start by destructuring the article prop and the styles object defined below the class.

这里有很多事情。 首先,我们首先要破坏 article属性和在class下定义styles对象

Inside the render method, we define the time constant to store the time when the article was published. We use the moment library to convert the date to the time passed since then, and we pass publishedAt or time from now if publishedAt is null.

在render方法内部,我们定义了时间常数来存储文章发布的时间。 我们使用矩型库将日期转换为从那时起经过的时间 ,并且如果publishedAtnull ,则传递publishedAt 时间从现在开始的时间

defaultImg is assigned an image URL in case the URL of the article image is null.

defaultImg图片的网址为null, defaultImg分配图片网址。

The render method returns TouchableNativeFeedback to handle when the user presses the card. We pass it some props: useForground , which tells the element to use the foreground when displaying the ripple effect on the card, and onPress , which takes a function and executes it when the user presses the card. We passed () => Linking.openUrl(url) , which will simply open the URL to the full article when we press the card.

当用户按下卡时,render方法返回TouchableNativeFeedback进行处理。 我们为它传递了一些道具: useForground ,它告诉元素在卡片上显示波纹效果时使用前景; onPress ,它接受一个函数并在用户按下卡片时执行它。 我们通过了() => Linking.openUrl(u rl),当我们按下卡片时,它将简单地打开完整文章的URL。

The card takes three props: featuredTitle , which is a title placed over the image, featuredTitleStyle to style it, and image which is the article image from the article prop. Otherwise, if its null , it’s going to be the defaultImg .

该卡具有三个道具: featuredTitle (在图像上放置标题), featuredTitleStyle在样式上为其设置样式)和image即来自商品道具的商品图像)。 否则,如果其为null ,它将是defaultImg

..  featuredTitle={title}  featuredTitleStyle={featuredTitleStyle}  image={{ uri: urlToImage || defaultImg }}..

As for the text element, it will hold the description for the article.

至于文字元素,它将包含文章的描述。

<Text style={{ marginBottom: 10 }}>{description}</Text>

We added a divider to separate the description from time and source name.

我们添加了一个分隔符以将描述与 时间和来源名称

<Divider style={{ backgroundColor: '#dfe6e9' }} />

Below the Divider , we have a View that contains the source name and the time the article was published.

Divider下方,我们有一个View ,其中包含源名称和文章发布的时间。

..<View   style={{ flexDirection: ‘row’, justifyContent: ‘space-between’ }} >   <Text style={noteStyle}>{source.name.toUpperCase()}</Text>  <Text style={noteStyle}>{time}</Text></View>..

After the class, we defined the styles for these components.

class ,我们定义了这些组件的样式。

Now if we run the app:

现在,如果我们运行该应用程序:

There you go! The source code for the app is available on GitHub: HERE, feel free to fork it.

你去! 该应用程序的源代码可在GitHub上找到: 此处,请随意进行分叉。

I hope you enjoyed my article! If you have any questions at all, feel free to comment or reach me on twitter and I will definitely help :)

希望您喜欢我的文章! 如果您有任何疑问,请随时在Twitter上发表评论或与我联系,我绝对会有所帮助的:)

?Buy me a coffee?

你给我一杯咖啡吗?

Next Story ?How to build native desktop apps with JavaScript

下一个故事? 可以使用JavaScript构建本机桌面应用程序

翻译自: https://www.freecodecamp.org/news/create-a-news-app-using-react-native-ced249263627/

 类似资料: