Skip to Content
React学习手册
book

React学习手册

by Alex Banks, Eve Porcello
December 2017
Intermediate to advanced
329 pages
6h 9m
Chinese
China Electric Power Press Ltd.
Content preview from React学习手册
Props
State
和组件树
111
6
-
1
React属性验证
类型
验证器
数组
React.PropTypes.array
布尔值
React.PropTypes.bool
函数
React.PropTypes.func
数字
React.PropTypes.number
对象
React.PropTypes.object
字符串
React.PropTypes.string
在这一节中,我们将为菜谱应用创建一个
Summary
组件。这个
Summary
件将会显示菜
谱的标题,以及食材成分和烹饪步骤的数目(见图
6-1
)。
6
-
1
Baked Salmon使用Summary组件描述的输出结果
为了显示这些数据,我们必须为
Summary
组件提供以下三种属性:标题,食材成分数
组和烹饪步骤数组。现在希望对这些属性进行验证,从而确保第一个属性是字符串类
型,其余的是数组类型,并且在它们无法通过属性验证时,提供默认参数。如何实现
属性验证功能取决于组件是如何创建的。无状态函数式组件和
ES6
的类有多种实现属
性验证的方法。
首先,让我们来看看用户应使用属性验证的原因,以及如何在
React.createClass
建的组件中实现它。
使用
createClass
验证
Props
我们需要理解验证组件属性为何如此重要的原因。考虑下面这个
Summary
组件的代码
实现:
const Summary = createClass({
displayName: "Summary",
render() {
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

React快速上手开发

React快速上手开发

Stoyan Stefanov
C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普

Publisher Resources

ISBN: 9787519814236