这里我们在组件声明之前就定义了propTypes,异常直不雅。我们可以这么做是因为js的函数名晋升机制。
Destructuring Props and defaultProps(解构props和defaultProps)
我们的组件是一个函数,props作为函数的入参被传递进来。我们可以按照如下方法对组件进行扩大:
我们可以给参数设置默认值,作为defaultProps。如不雅expanded是undefined,就将其设置为false。(这种设置默认值的方法,对于对象类的入参异常有效,可以避免`can't read property XXXX of undefined的缺点)
不要应用es6箭头函数的写法:
- const ExpandableForm = ({ onExpand, expanded, children }) => {
这种写法中,函数实际是匿名函数。如不雅精确地应用了babel则不盘考题,然则如不雅没有,运行时就会导致一些缺点,异常不便利调试。
给setState传入一个函数作为参数(passing setState a Function)
别的,在Jest,一个react的测试库,中应用匿名函数也会导致一些问题。因为应用匿名函数可能会出现一些潜在的问题,我们推荐应用function,而不是const。
Wrapping
译者注:今朝CSS in JS可以应用css modules筹划来解决,webpack的css-loader已经供给了该功能
在函数组件中不克不及应用装潢器,我们可以将其作为入参传给observer函数
- import React from 'react'
- import { observer } from 'mobx-react'
- import { func, bool } from 'prop-types'
- import './styles/Form.css'
- ExpandableForm.propTypes = {
- onSubmit: func.isRequired,
- expanded: bool,
- onExpand: func.isRequired
- }
- function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) {
- const formStyle = expanded ? {height: 'auto'} : {height: 0}
- return (
- <form style={formStyle} onSubmit={onSubmit}>
- {children}
- <button onClick={onExpand}>Expand</button>
- </form>
- )
- }
- export default observer(ExpandableForm)
完全组件如下所示:
- import React from 'react'
- import { observer } from 'mobx-react'
- import { func, bool } from 'prop-types'
- // Separate local imports from dependencies
- import './styles/Form.css'
- // Declare propTypes here, before the component (taking advantage
推荐阅读
引言反射基本p.s: 本文须要读者对反射机制的API有必定程度的懂得,如不雅之前没有接触过的话,建议先看一下官方文档的Quick Start。在应用反射机制之前,起首我们先来看一下若何获取一个对>>>详细阅读
本文标题:编写react组件最佳实践
地址:http://www.17bianji.com/lsqh/35286.html
1/2 1