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:

构建应用程序的要求:

  • A basic understanding of the JavaScript language.

    对JavaScript的基本了解 语言

  • Install: Node.js, react native using npm.

    安装: Node.js,使用npm进行 本机响应 。

  • Libraries used: moment, react-native, react-native-elements.

    使用的库: moment , react-native , react-native-elements 。

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/

如何使用React Native构建新闻应用相关推荐

  1. 如何使用React Native构建嵌套的抽屉菜单

    by Dhruvdutt Jadhav 由Dhruvdutt Jadhav 如何使用React Native构建嵌套的抽屉菜单 (How to build a nested drawer menu w ...

  2. 使用React Native构建类似Tinder的加载器

    在这篇文章中我会尝试描述在React Native中构建一个类似Tinder的加载器所遇到的调整我把它分成三个挑战. 挑战1:布局 在上面的截图中,你可以看到头像和它后面的圆,都在屏幕正中间. 感谢 ...

  3. 使用React Native和Spring Boot构建一个移动应用

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. Reac ...

  4. 构建了我的第一个React Native应用程序之后,我现在确信这是未来。

    by Taylor Milliman 泰勒·米利曼(Taylor Milliman) 构建了我的第一个React Native应用程序之后,我现在确信这是未来. (After building my ...

  5. 如何构建具有实时搜索功能的React Native FlatList

    by Vikrant Negi 通过Vikrant Negi 如何构建具有实时搜索功能的React Native FlatList (How to build a React Native FlatL ...

  6. 我如何为我的第一个自由客户构建第一个React Native应用程序

    by Charlie Jeppsson 查理·杰普森(Charlie Jeppsson) 我如何为我的第一个自由客户构建第一个React Native应用程序 (How I built my firs ...

  7. React Native初探

    React Native初探 转自:博客园 叶小钗  前言 很久之前就想研究React Native了,但是一直没有落地的机会,我一直认为一个技术要有落地的场景才有研究的意义,刚好最近迎来了新的APP ...

  8. React Native Expo开发的OW移动端项目

    iOS演示 开源地址 GitHub Gitee 项目地址 Andorid 版 Android Expo 版(需 Expo 移动端(Android/iOS)) Expo 简介 项目基于Expo的 Rea ...

  9. Shoutem旨在成为React Native移动应用领域的WordPress

    近日,Shoutem推出了新的基于React Native的应用构建器,为开发人员提供了移动应用领域的WordPress. \\ Shoutem让开发人员可以使用一个可视化环境快速创建基于React ...

最新文章

  1. Android 接口回调
  2. Linux内核源代码情景分析-fork()
  3. “进度条”博客——第三周
  4. 【Linux 内核】进程管理 task_struct 结构体 ④ ( comm 字段 | 进程优先级字段 | cpus_ptr 字段 | mm、active_mm 字段 | fs 字段 )
  5. 【Scratch】青少年蓝桥杯_每日一题_3.23_骰子
  6. 星星评价控件android开发_android自定义星级评分控件,可实现只显示实心星星
  7. noi 4982 踩方格
  8. centos6.5+jexus5.6.3+mono 3.10实践,让asp.net在linux上飞一会儿
  9. HLSL编译工具—FXC
  10. windows--bat--右键菜单
  11. The Gradient Operator
  12. 2016CCPC东北地区大学生程序设计竞赛题解
  13. Nhibernate HQL 匿名类(严格说是map的使用以及构造函数的使用
  14. DOSBox安装及使用教程
  15. 利用opencv 做一个疲劳检测系统(2)
  16. cmos逻辑门传输延迟时间_什么是TTL电平、CMOS电平?区别是什么?
  17. 技术岗的职业规划_技术人员职业规划精选范文
  18. mysql preparing状态_【Docker】在集群中部署应用为什么始终是Preparing状态
  19. Win11如何隐藏输入法悬浮窗?
  20. MFC 实现打印机打印功能

热门文章

  1. c++,输入一个整数,判断它是奇数还是偶数
  2. 工作的未来是DAO,收入的未来是「X-to-earn」 |链捕手
  3. 罗斯柴尔德家族:“大道无形”世界首富
  4. 26.Odoo产品分析 (三) – 人力资源板块(6) – 工资表(2)
  5. Tikz教程:一个异步FIFO设计步骤示意图的画法
  6. HTML打造动漫人物,好莱坞顶级制作联袂打造!《和平精英》首部官方角色·吉莉 动画短片发布...
  7. 三维旋转矩阵;东北天坐标系(ENU);地心地固坐标系(ECEF);大地坐标系(Geodetic);经纬度对应圆弧距离
  8. 车内看车头正不正技巧_【交通安全提示】科二曲线行驶技巧图解,蜀黍手把手教你过关!...
  9. 利用Amber热力学积分计算相对自由能变化
  10. 国产CPU整体性能和发展情况一览表