文档章节

React - Guide to Props: Passing The Correct Props

Kolosek
 Kolosek
发布于 2018/03/26 16:11
字数 568
阅读 13
收藏 0

Previously we've learned how to pass props in react and also how to indirectly communicate between components using props. Today, we're getting to the finale of props guide series, where we'll talk about how to check whether we passed correct props.

React props - Make sure you are typechecking

As the application you're working on grows, you'll definitely want to add some kind of prop typechecking - you don't want bugs you'll work on for hours or days before you realize you just sent an empty array instead of an object!

You can be a bit more extreme and use something like Typescript to cover your whole app with checks. While TypeScript can be quite useful and nice, there's no need for this - you don't need to enforce typechecking of every single function and variable.

Defining PropTypes is not enough! Make sure you're also covering your code with tests!

React has built-in PropTypes so you can typecheck easily. Basically, the idea is that inside of propTypes you define the type for each of the props used in the component. Here's our example component we'll be defining PropTypes for:

class Input extends Component {
    ...
    handleChange = (event) => {
        const newValue = event.target.value;
        this.props.updateParent(newValue);
    }
    ...
    render() {
        return (
            <input
                onChange={this.handleChange}
                placeholder={this.props.placeholder}
                type="text"
                value={this.props.value}
            />
        )
    }
}

The propTypes will look like this:

    Input.propTypes = {
        placeholder: PropTypes.string,
        updateParent: PropTypes.func.isRequired,
        value: PropTypes.string.isRequired,
    };

You have probably noticed that for updateParent and value we are using isRequired after prop type definition. This is to specify that the prop must be passed to a component, and that something will probably break if it's not done so.

If rendering a list sent as a prop, always make sure it's either required or default value is set!

On the other hand, a placeholder is not required. For optional props like this one, you might want to define a default value when nothing is pressed. You can achieve that by defining defaultPropsfor a component:

    Input.defaultProps = {
        placeholder: "Default placeholder",
    };

Besides the standard types, you can also add a typecheck whether a prop is an instance or some class:

   Parent.propTypes = {
        inputChild: PropTypes.instanceOf(Input),
    };

You can, as well, specify that prop can be any data type, by using PropTypes.any:

   Parent.propTypes = {
       anyValue: PropTypes.any,
   };

Try to avoid any, it's like not defining prop types at all - if you pass an empty array instead of an actual false value, that conditional rendering won't work as you expect!

PropTypes do not limit you to use just predefined type validators, you can also define your own. For more useful information on typechecking, take a look at the official guide, as it contains all the answers to questions you might have.

For all of the issues found while typechecking you will get notified in a console.

We strongly recommend that you configure eslint to require props validations for all components. This way you won't forget to define propTypes for your components, so you won't miss out some of the accidental issues you might have made during the coding.

You can also configure eslint to enforce defining of default values for props that are not required if you prefer to. This, although nice to have for consistency over the component instances, is not of such a big importance.

We hope you enjoyed this article and learned something new and useful, or at least freshened up your knowledge a bit!

This article is originally published on Kolosek Blog.

© 著作权归作者所有

Kolosek
粉丝 0
博文 29
码字总数 20461
作品 0
塞尔维亚
CEO
私信 提问
fondadam/reactjs-init

reactjs-init 中文版 A command line tool that generates a React.js project boilerplate. Getting Started $ npm install -g reactjs-init Commands Generate a boilerplate. $ reactjs ......

fondadam
2016/05/14
0
0
React & Redux in TypeScript - 静态类型指南

翻译自 react-redux-typescript-guide,作者:Piotrek Witek 翻译自 TypeScriptでRedux Thunkを使う,作责:Yusuke Mori 参考文章 TypeScript 2.8下的终极React组件模式 概述:最近在学习 re...

FatGe
03/25
0
0
使用Formik轻松开发更高质量的React表单(三)解析

提醒 关于 is a component that helps you with building forms. It uses a render props pattern made popular by libraries like React Motion and React Router. import React from 'rea......

googlingman
2018/07/30
0
0
陈民/react-select2

lovli.js A starter kit which allows you to develop realtime applications in minutes. Demo: lovli.neschkudla.at Stack facebook/react - View reactjs/redux - App State rethinkdb/ho......

陈民
2016/05/13
0
0
Framework7 3.4.2 发布,专注 iOS 美学的 HTML 框架

Framework7 3.4.2 发布了,Framework7 是一个开源的全功能 HTML 框架,用于构建具有 iOS 和 Android 原生外观的混合移动应用程序或 Web 应用程序。同时 Framework7 也是独立的原型应用工具。...

h4cd
2018/10/13
1K
2

没有更多内容

加载失败,请刷新页面

加载更多

Flink Graph生成及Hash生成分析

222

MrPei
26分钟前
3
0
[译]Android Activity 和 Fragment 状态保存与恢复的最佳实践

https://blog.csdn.net/growing_tree/article/details/53759564 https://blog.csdn.net/u013588712/article/details/54691791...

shzwork
26分钟前
2
0
调用第三方快递鸟物流单号查询接口API代码示例

最近进行网站后台开发,需要实现物流的即时查询,发现之前集成的 快递100物流查询 API ——【PHP 快递查询源码资源】 已经不能正常使用了; 为了方便以后的业务需求,经过比较,最后选择使用...

程序的小猿
34分钟前
4
0
java Poi 操作执行excel 文件中函数问题

poi 读取excel 文件,当excel 有函数时,poi直接读取返回的是excel 函数,并不能返回函数计算结果: 解决步骤: sheet.setForceFormulaRecalculation(true); 判断该列格式是否为...

早a
41分钟前
5
0
js模拟实现输入框input事件

直接修改value值是无法触发对应元素的事件的。 通过发送输入框input事件了, 可以触发。 这里简单封装了一个方法. window.inputValue = function (dom, st) { var evt = new InputEvent('i...

開援带碼
42分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部