编写react组件更优实践

开发 前端
我最开始学习react的时候,看到过各种各样编写组件的方式,不同教程中提出的方法往往有很大不同。当时虽说react这个框架已经十分成熟,但是似乎还没有一种公认正确的使用方法。过去几年中,我们团队编写了很多react组件,我们对实现方法进行了不断的优化,直到满意。

编写react组件***实践

我最开始学习react的时候,看到过各种各样编写组件的方式,不同教程中提出的方法往往有很大不同。当时虽说react这个框架已经十分成熟,但是似乎还没有一种公认正确的使用方法。过去几年中,我们团队编写了很多react组件,我们对实现方法进行了不断的优化,直到满意。

本文介绍了我们在实践中的***实践方式,希望能对无论是初学者还是有经验的开发者来说都有一定的帮助。

在我们开始之前,有几点需要说明:

  • 我们是用es6和es7语法
  • 如果你不了解展示组件和容器组件的区别,可以先阅读这篇文章
  • 如果你有任何建议、问题或者反馈,可以给我们留言

Class Based Components (基于类的组件)

Class based components 有自己的state和方法。我们会尽可能谨慎的使用这些组件,但是他们有自己的使用场景。

接下来我们就一行一行来编写组件。

导入CSS

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import ExpandableForm from './ExpandableForm' 
  6.  
  7. import './styles/ProfileContainer.css'  

我很喜欢CSS in JS,但是它目前还是一种新的思想,成熟的解决方案还未产生。我们在每个组件中都导入了它的css文件。

译者注:目前CSS in JS可以使用css modules方案来解决,webpack的css-loader已经提供了该功能

我们还用一个空行来区分自己的依赖。

译者注:即第4、5行和第1、2行中间会单独加行空行。

初始化state

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import ExpandableForm from './ExpandableForm' 
  6.  
  7. import './styles/ProfileContainer.css' 
  8.  
  9. export default class ProfileContainer extends Component { 
  10.  
  11. state = { expanded: false }  

你也可以在constructor中初始化state,不过我们更喜欢这种简洁的方式。我们还会确保默认导出组件的class。

propTypes 和 defaultProps

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import { string, object } from 'prop-types' 
  6.  
  7. import ExpandableForm from './ExpandableForm' 
  8.  
  9. import './styles/ProfileContainer.css' 
  10.  
  11. export default class ProfileContainer extends Component { 
  12.  
  13. state = { expanded: false } 
  14.  
  15. static propTypes = { 
  16.  
  17. model: object.isRequired, 
  18.  
  19. title: string 
  20.  
  21.  
  22. static defaultProps = { 
  23.  
  24. model: { 
  25.  
  26. id: 0 
  27.  
  28. }, 
  29.  
  30. title: 'Your Name' 
  31.  
  32.  

propTypes和defaultProps是静态属性,应该尽可能在代码的顶部声明。这两个属性起着文档的作用,应该能够使阅读代码的开发者一眼就能够看到。如果你正在使用react 15.3.0或者更高的版本,使用prop-types,而不是React.PropTypes。你的所有组件,都应该有propTypes属性。

方法

  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import { string, object } from 'prop-types' 
  6.  
  7. import ExpandableForm from './ExpandableForm' 
  8.  
  9. import './styles/ProfileContainer.css' 
  10.  
  11. export default class ProfileContainer extends Component { 
  12.  
  13. state = { expanded: false } 
  14.  
  15. static propTypes = { 
  16.  
  17. model: object.isRequired, 
  18.  
  19. title: string 
  20.  
  21.  
  22. static defaultProps = { 
  23.  
  24. model: { 
  25.  
  26. id: 0 
  27.  
  28. }, 
  29.  
  30. title: 'Your Name' 
  31.  
  32.  
  33. handleSubmit = (e) => { 
  34.  
  35. e.preventDefault() 
  36.  
  37. this.props.model.save() 
  38.  
  39.  
  40. handleNameChange = (e) => { 
  41.  
  42. this.props.model.changeName(e.target.value) 
  43.  
  44.  
  45. handleExpand = (e) => { 
  46.  
  47. e.preventDefault() 
  48.  
  49. this.setState({ expanded: !this.state.expanded }) 
  50.  
  51.  

使用class components,当你向子组件传递方法的时候,需要确保这些方法被调用时有正确的this值。通常会在向子组件传递时使用this.handleSubmit.bind(this)来实现。当然,使用es6的箭头函数写法更加简洁。

译者注:也可以在constructor中完成方法的上下文的绑定:

  1. constructor() { 
  2.  
  3. this.handleSubmit = this.handleSubmit.bind(this); 
  4.  
  5.  

给setState传入一个函数作为参数(passing setState a Function)

在上文的例子中,我们是这么做的:

  1. this.setState({ expanded: !this.state.expanded }) 

setState实际是异步执行的,react因为性能原因会将state的变化整合,再一起处理,因此当setState被调用的时候,state并不一定会立即变化。

这意味着在调用setState的时候你不能依赖当前的state值——因为你不能确保setState真正被调用的时候state究竟是什么。

解决方案就是给setState传入一个方法,该方法接收上一次的state作为参数。

this.setState(prevState => ({ expanded: !prevState.expanded })

解构props

  1. import React, { Component } from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { string, object } from 'prop-types' 
  4. import ExpandableForm from './ExpandableForm' 
  5. import './styles/ProfileContainer.css' 
  6. export default class ProfileContainer extends Component { 
  7.   state = { expanded: false } 
  8.   
  9.   static propTypes = { 
  10.     model: object.isRequired, 
  11.     title: string 
  12.   } 
  13.   
  14.   static defaultProps = { 
  15.     model: { 
  16.       id: 0 
  17.     }, 
  18.     title: 'Your Name' 
  19.   } 
  20.   handleSubmit = (e) => { 
  21.     e.preventDefault() 
  22.     this.props.model.save() 
  23.   } 
  24.    
  25.   handleNameChange = (e) => { 
  26.     this.props.model.changeName(e.target.value) 
  27.   } 
  28.    
  29.   handleExpand = (e) => { 
  30.     e.preventDefault() 
  31.     this.setState(prevState => ({ expanded: !prevState.expanded })) 
  32.   } 
  33.    
  34.   render() { 
  35.     const { 
  36.       model, 
  37.       title 
  38.     } = this.props 
  39.     return (  
  40.       <ExpandableForm  
  41.         onSubmit={this.handleSubmit}  
  42.         expanded={this.state.expanded}  
  43.         onExpand={this.handleExpand}> 
  44.         <div> 
  45.           <h1>{title}</h1> 
  46.           <input 
  47.             type="text" 
  48.             value={model.name
  49.             onChange={this.handleNameChange} 
  50.             placeholder="Your Name"/> 
  51.         </div> 
  52.       </ExpandableForm> 
  53.     ) 
  54.   } 
  55.  

对于有很多props的组件来说,应当像上述写法一样,将每个属性解构出来,且每个属性单独一行。

装饰器(Decorators)

  1. @observer 
  2.  
  3. export default class ProfileContainer extends Component {  

如果你正在使用类似于mobx的状态管理器,你可以按照上述方式描述你的组件。这种写法与将组件作为参数传递给一个函数效果是一样的。装饰器(decorators)是一种非常灵活和易读的定义组件功能的方式。我们使用mobx和mobx-models来结合装饰器进行使用。

如果你不想使用装饰器,可以按照如下方式来做:

  1. class ProfileContainer extends Component { 
  2.  
  3. // Component code 
  4.  
  5.  
  6. export default observer(ProfileContainer)  

闭包

避免向子组件传入闭包,如下:

  1. <input 
  2.             type="text" 
  3.             value={model.name
  4.             // onChange={(e) => { model.name = e.target.value }} 
  5.             // ^ 不要这样写,按如下写法: 
  6.             onChange={this.handleChange} 
  7.             placeholder="Your Name"/>  

原因在于:每次父组件重新渲染时,都会创建一个新的函数,并传给input。

如果这个input是个react组件的话,这会导致无论该组件的其他属性是否变化,该组件都会重新render。

而且,采用将父组件的方法传入的方式也会使得代码更易读,方便调试,同时也容易修改。

完整代码如下:

  1. import React, { Component } from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { string, object } from 'prop-types' 
  4. // Separate local imports from dependencies 
  5. import ExpandableForm from './ExpandableForm' 
  6. import './styles/ProfileContainer.css' 
  7.  
  8. // Use decorators if needed 
  9. @observer 
  10. export default class ProfileContainer extends Component { 
  11.   state = { expanded: false } 
  12.   // Initialize state here (ES7) or in a constructor method (ES6) 
  13.   
  14.   // Declare propTypes as static properties as early as possible 
  15.   static propTypes = { 
  16.     model: object.isRequired, 
  17.     title: string 
  18.   } 
  19.  
  20.   // Default props below propTypes 
  21.   static defaultProps = { 
  22.     model: { 
  23.       id: 0 
  24.     }, 
  25.     title: 'Your Name' 
  26.   } 
  27.  
  28.   // Use fat arrow functions for methods to preserve context (this will thus be the component instance) 
  29.   handleSubmit = (e) => { 
  30.     e.preventDefault() 
  31.     this.props.model.save() 
  32.   } 
  33.    
  34.   handleNameChange = (e) => { 
  35.     this.props.model.name = e.target.value 
  36.   } 
  37.    
  38.   handleExpand = (e) => { 
  39.     e.preventDefault() 
  40.     this.setState(prevState => ({ expanded: !prevState.expanded })) 
  41.   } 
  42.  
  43.   render() { 
  44.     // Destructure props for readability 
  45.     const { 
  46.       model, 
  47.       title 
  48.     } = this.props 
  49.     return (  
  50.       <ExpandableForm  
  51.         onSubmit={this.handleSubmit}  
  52.         expanded={this.state.expanded}  
  53.         onExpand={this.handleExpand}> 
  54.         // Newline props if there are more than two 
  55.         <div> 
  56.           <h1>{title}</h1> 
  57.           <input 
  58.             type="text" 
  59.             value={model.name
  60.             // onChange={(e) => { model.name = e.target.value }} 
  61.             // Avoid creating new closures in the render method- use methods like below 
  62.             onChange={this.handleNameChange} 
  63.             placeholder="Your Name"/> 
  64.         </div> 
  65.         </ExpandableForm> 
  66.     ) 
  67.   } 
  68.  

函数组件(Functional Components)

这些组件没有state和方法。它们是纯净的,非常容易定位问题,可以尽可能多的使用这些组件。

propTypes

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4.  
  5. import './styles/Form.css' 
  6. ExpandableForm.propTypes = { 
  7.   onSubmit: func.isRequired, 
  8.   expanded: bool 
  9. // Component declaration  

这里我们在组件声明之前就定义了propTypes,非常直观。我们可以这么做是因为js的函数名提升机制。

Destructuring Props and defaultProps(解构props和defaultProps)

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4.  
  5. import './styles/Form.css' 
  6. ExpandableForm.propTypes = { 
  7.   onSubmit: func.isRequired, 
  8.   expanded: bool, 
  9.   onExpand: func.isRequired 
  10. function ExpandableForm(props) { 
  11.   const formStyle = props.expanded ? {height: 'auto'} : {height: 0} 
  12.   return ( 
  13.     <form style={formStyle} onSubmit={props.onSubmit}> 
  14.       {props.children} 
  15.       <button onClick={props.onExpand}>Expand</button> 
  16.     </form> 
  17.   ) 
  18.  

我们的组件是一个函数,props作为函数的入参被传递进来。我们可以按照如下方式对组件进行扩展:

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4. import './styles/Form.css' 
  5. ExpandableForm.propTypes = { 
  6.   onSubmit: func.isRequired, 
  7.   expanded: bool, 
  8.   onExpand: func.isRequired 
  9. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
  10.   const formStyle = expanded ? {height: 'auto'} : {height: 0} 
  11.   return ( 
  12.     <form style={formStyle} onSubmit={onSubmit}> 
  13.       {children} 
  14.       <button onClick={onExpand}>Expand</button> 
  15.     </form> 
  16.   ) 
  17.  

我们可以给参数设置默认值,作为defaultProps。如果expanded是undefined,就将其设置为false。(这种设置默认值的方式,对于对象类的入参非常有用,可以避免`can't read property XXXX of undefined的错误)

不要使用es6箭头函数的写法:

  1. const ExpandableForm = ({ onExpand, expanded, children }) => { 

这种写法中,函数实际是匿名函数。如果正确地使用了babel则不成问题,但是如果没有,运行时就会导致一些错误,非常不方便调试。

另外,在Jest,一个react的测试库,中使用匿名函数也会导致一些问题。由于使用匿名函数可能会出现一些潜在的问题,我们推荐使用function,而不是const。

Wrapping

在函数组件中不能使用装饰器,我们可以将其作为入参传给observer函数

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4.  
  5. import './styles/Form.css' 
  6. ExpandableForm.propTypes = { 
  7.   onSubmit: func.isRequired, 
  8.   expanded: bool, 
  9.   onExpand: func.isRequired 
  10. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
  11.   const formStyle = expanded ? {height: 'auto'} : {height: 0} 
  12.   return ( 
  13.     <form style={formStyle} onSubmit={onSubmit}> 
  14.       {children} 
  15.       <button onClick={onExpand}>Expand</button> 
  16.     </form> 
  17.   ) 
  18. export default observer(ExpandableForm)  

完整组件如下所示:

  1. import React from 'react' 
  2. import { observer } from 'mobx-react' 
  3. import { func, bool } from 'prop-types' 
  4. // Separate local imports from dependencies 
  5. import './styles/Form.css' 
  6.  
  7. // Declare propTypes here, before the component (taking advantage of JS function hoisting) 
  8. // You want these to be as visible as possible 
  9. ExpandableForm.propTypes = { 
  10.   onSubmit: func.isRequired, 
  11.   expanded: bool, 
  12.   onExpand: func.isRequired 
  13.  
  14. // Destructure props like so, and use default arguments as a way of setting defaultProps 
  15. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
  16.   const formStyle = expanded ? { height: 'auto' } : { height: 0 } 
  17.   return ( 
  18.     <form style={formStyle} onSubmit={onSubmit}> 
  19.       {children} 
  20.       <button onClick={onExpand}>Expand</button> 
  21.     </form> 
  22.   ) 
  23.  
  24. // Wrap the component instead of decorating it 
  25. export default observer(ExpandableForm)  

在JSX中使用条件判断(Conditionals in JSX)

有时候我们需要在render中写很多的判断逻辑,以下这种写法是我们应该要避免的:

 

目前有一些库来解决这个问题,但是我们没有引入其他依赖,而是采用了如下方式来解决:

 

这里我们采用立即执行函数的方式来解决问题,将if语句放到立即执行函数中,返回任何你想返回的。需要注意的是,立即执行函数会带来一定的性能问题,但是对于代码的可读性来说,这个影响可以忽略。

同样的,当你只希望在某种情况下渲染时,不要这么做:

  1.   isTrue 
  2.    ? <p>True!</p> 
  3.    : <none/> 
  4.  

而应当这么做:

  1.  
  2. isTrue && 
  3.  
  4. <p>True!</p> 
  5.  
  6.  

(全文完) 

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2017-02-28 21:57:05

React组件

2023-12-21 10:26:30

​​Prettier

2022-05-13 08:48:50

React组件TypeScrip

2019-07-22 10:42:11

React组件前端

2019-07-20 23:30:48

开发技能代码

2021-12-13 14:37:37

React组件前端

2021-12-07 08:16:34

React 前端 组件

2020-06-01 09:40:06

开发ReactTypeScript

2020-06-03 16:50:24

TypeScriptReact前端

2022-08-19 09:01:59

ReactTS类型

2017-01-23 21:05:00

AndroidApp启动优化

2016-08-23 10:50:50

WebJavascript缓存

2017-04-06 09:56:52

大数据数据结转技术架构

2023-07-21 01:12:30

Reactfalse​变量

2017-06-02 10:25:26

Java异常处理

2021-06-08 09:35:11

Cleaner ReaReact开发React代码

2017-05-25 10:58:08

HBase数据库操作系统

2017-01-12 13:26:38

大数据深度学习大数据技术

2022-03-16 17:01:35

React18并发的React组件render

2016-10-08 18:02:21

SQL Server安装设置与实践
点赞
收藏

51CTO技术栈公众号