此文翻译自这里

当我刚开始写React的时候,我看过很多写组件的方法。一百篇教程就有一百种写法。虽然React本身已经成熟了,但是如何使用它似乎还没有一个“正确”的方法。所以我(作者)把我们团队这些年来总结的使用React的经验总结在这里。希望这篇文字对你有用,不管你是初学者还是老手。

开始前:

  • 我们使用ES6、ES7语法
  • 如果你不是很清楚展示组件和容器组件的区别,建议您从阅读这篇文章开始
  • 如果您有任何的建议、疑问都清在评论里留言

基于类的组件

现在开发React组件一般都用的是基于类的组件。下面我们就来一行一样的编写我们的组件:

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

我很喜欢css in javascript。但是,这个写样式的方法还是太新了。所以我们在每个组件里引入css文件。而且本地引入的import和全局的import会用一个空行来分割。

初始化State

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

您可以使用了老方法在constructor里初始化state。更多相关可以看这里。但是我们选择更加清晰的方法。

同时,我们确保在类前面加上了export default。(译者注:虽然这个在使用了redux的时候不一定对)。

propTypes and defaultProps

  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. static propTypes = {
  9. model: object.isRequired,
  10. title: string
  11. }
  12. static defaultProps = {
  13. model: {
  14. id: 0
  15. },
  16. title: 'Your Name'
  17. }
  18. // ...
  19. }

propTypesdefaultProps是静态属性。尽可能在组件类的的前面定义,让其他的开发人员读代码的时候可以立刻注意到。他们可以起到文档的作用。

如果你使用了React 15.3.0或者更高的版本,那么需要另外引入prop-types包,而不是使用React.PropTypes。更多内容移步这里

你所有的组件都应该有prop types

方法

  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. static propTypes = {
  9. model: object.isRequired,
  10. title: string
  11. }
  12. static defaultProps = {
  13. model: {
  14. id: 0
  15. },
  16. title: 'Your Name'
  17. }
  18. handleSubmit = (e) => {
  19. e.preventDefault()
  20. this.props.model.save()
  21. }
  22. handleNameChange = (e) => {
  23. this.props.model.changeName(e.target.value)
  24. }
  25. handleExpand = (e) => {
  26. e.preventDefault()
  27. this.setState({ expanded: !this.state.expanded })
  28. }
  29. // ...
  30. }

在类组件里,当你把方法传递给子组件的时候,需要确保他们被调用的时候使用的是正确的this。一般都会在传给子组件的时候这么做:this.handleSubmit.bind(this)

使用ES6的箭头方法就简单多了。它会自动维护正确的上下文(this)。

给setState传入一个方法

在上面的例子里有这么一行:

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

setState其实是异步的!React为了提高性能,会把多次调用的setState放在一起调用。所以,调用了setState之后state不一定会立刻就发生改变。

所以,调用setState的时候,你不能依赖于当前的state值。因为i根本不知道它是值会是神马。

解决方法:给setState传入一个方法,把调用前的state值作为参数传入这个方法。看看例子:

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

感谢Austin Wood的帮助。

拆解组件

  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. static propTypes = {
  9. model: object.isRequired,
  10. title: string
  11. }
  12. static defaultProps = {
  13. model: {
  14. id: 0
  15. },
  16. title: 'Your Name'
  17. }
  18. handleSubmit = (e) => {
  19. e.preventDefault()
  20. this.props.model.save()
  21. }
  22. handleNameChange = (e) => {
  23. this.props.model.changeName(e.target.value)
  24. }
  25. handleExpand = (e) => {
  26. e.preventDefault()
  27. this.setState(prevState => ({ expanded: !prevState.expanded }))
  28. }
  29. render() {
  30. const {
  31. model,
  32. title
  33. } = this.props
  34. return (
  35. <ExpandableForm
  36. onSubmit={this.handleSubmit}
  37. expanded={this.state.expanded}
  38. onExpand={this.handleExpand}>
  39. <div>
  40. <h1>{title}</h1>
  41. <input
  42. type="text"
  43. value={model.name}
  44. onChange={this.handleNameChange}
  45. placeholder="Your Name"/>
  46. </div>
  47. </ExpandableForm>
  48. )
  49. }
  50. }

有多行的props的,每一个prop都应该单独占一行。就如上例一样。要达到这个目标最好的方法是使用一套工具:Prettier

装饰器(Decorator)

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

如果你了解某些库,比如mobx,你就可以使用上例的方式来修饰类组件。装饰器就是把类组件作为一个参数传入了一个方法。

装饰器可以编写更灵活、更有可读性的组件。如果你不想用装饰器,你可以这样:

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

闭包

尽量避免在子组件中传入闭包,如:

  1. <input
  2. type="text"
  3. value={model.name}
  4. // onChange={(e) => { model.name = e.target.value }}
  5. // ^ Not this. Use the below:
  6. onChange={this.handleChange}
  7. placeholder="Your Name"/>

注意:如果input是一个React组件的话,这样自动触发它的重绘,不管其他的props是否发生了改变。

一致性检验是React最消耗资源的部分。不要把额外的工作加到这里。处理上例中的问题最好的方法是传入一个类方法,这样还会更加易读,更容易调试。如:

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

方法组件

这类组件没有state没有props,也没有方法。它们是纯组件,包含了最少的引起变化的内容。经常使用它们。

propTypes

  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. }
  9. // Component declaration

我们在组件的声明之前就定义了propTypes

分解Props和defaultProps

  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. }
  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. }
  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. }

现在我们也可以使用默认参数来扮演默认props的角色,这样有很好的可读性。如果expanded没有定义,那么我们就把它设置为false

但是,尽量避免使用如下的例子:

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

看起来很现代,但是这个方法是未命名的。

如果你的Babel配置正确,未命名的方法并不会是什么大问题。但是,如果Babel有问题的话,那么这个组件里的任何错误都显示为发生在 <>里的,这调试起来就非常麻烦了。

匿名方法也会引起Jest其他的问题。由于会引起各种难以理解的问题,而且也没有什么实际的好处。我们推荐使用function,少使用const

装饰方法组件

由于方法组件没法使用装饰器,只能把它作为参数传入别的方法里。

  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. }
  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. }
  19. export default observer(ExpandableForm)

只能这样处理: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. // Declare propTypes here, before the component (taking advantage of JS function hoisting)
  7. // You want these to be as visible as possible
  8. ExpandableForm.propTypes = {
  9. onSubmit: func.isRequired,
  10. expanded: bool,
  11. onExpand: func.isRequired
  12. }
  13. // Destructure props like so, and use default arguments as a way of setting defaultProps
  14. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) {
  15. const formStyle = expanded ? { height: 'auto' } : { height: 0 }
  16. return (
  17. <form style={formStyle} onSubmit={onSubmit}>
  18. {children}
  19. <button onClick={onExpand}>Expand</button>
  20. </form>
  21. )
  22. }
  23. // Wrap the component instead of decorating it
  24. export default observer(ExpandableForm)

条件判断

某些情况下,你会做很多的条件判断:

  1. <div id="lb-footer">
  2. {props.downloadMode && currentImage && !currentImage.video && currentImage.blogText
  3. ? !currentImage.submitted && !currentImage.posted
  4. ? <p>Please contact us for content usage</p>
  5. : currentImage && currentImage.selected
  6. ? <button onClick={props.onSelectImage} className="btn btn-selected">Deselect</button>
  7. : currentImage && currentImage.submitted
  8. ? <button className="btn btn-submitted" disabled>Submitted</button>
  9. : currentImage && currentImage.posted
  10. ? <button className="btn btn-posted" disabled>Posted</button>
  11. : <button onClick={props.onSelectImage} className="btn btn-unselected">Select post</button>
  12. }
  13. </div>

这么多层的条件判断可不是什么好现象。

有第三方库JSX-Control Statements可以解决这个问题。但是与其增加一个依赖,还不如这样来解决:

  1. <div id="lb-footer">
  2. {
  3. (() => {
  4. if(downloadMode && !videoSrc) {
  5. if(isApproved && isPosted) {
  6. return <p>Right click image and select "Save Image As.." to download</p>
  7. } else {
  8. return <p>Please contact us for content usage</p>
  9. }
  10. }
  11. // ...
  12. })()
  13. }
  14. </div>

使用大括号包起来的IIFE,然后把你的if表达式都放进去。返回你要返回的组件。

最后

再次,希望本文对你有用。如果你有什么好的意见或者建议的话请写在下面的评论里。谢谢!

编写React组件的最佳实践的更多相关文章

  1. 我们编写 React 组件的最佳实践

    刚接触 React 的时候,在一个又一个的教程上面看到很多种编写组件的方法,尽管那时候 React 框架已经相当成熟,但是并没有一个固定的规则去规范我们去写代码. 在过去的一年里,我们在不断的完善我们 ...

  2. React服务器渲染最佳实践

    源码地址:https://github.com/skyFi/dva-starter React服务器渲染最佳实践 dva-starter 完美使用 dva react react-router,最好用 ...

  3. 编写Shell脚本的最佳实践

    编写Shell脚本的最佳实践 http://kb.cnblogs.com/page/574767/ 需要记住的 代码有注释 #!/bin/bash # Written by steven # Name ...

  4. 《React设计模式与最佳实践》笔记

    书里的demo都是15.3.2以下版本的,有些demo用最新的react 16.x版本会报错,安装包的时候记得改一下版本   第一章 React 基础 命令式编程描述代码如何工作,而声明式编程则表明想 ...

  5. 编写Shell脚本的最佳实践,规范二

    需要养成的习惯如下: 代码有注释 #!/bin/bash # Written by steven # Name: mysqldump.sh # Version: v1.0 # Parameters : ...

  6. 编写 Shell 脚本的最佳实践

    转自:http://kb.cnblogs.com/page/574767/ 前言 由于工作需要,最近重新开始拾掇shell脚本.虽然绝大部分命令自己平时也经常使用,但是在写成脚本的时候总觉得写的很难看 ...

  7. React 代码共享最佳实践方式

    任何一个项目发展到一定复杂性的时候,必然会面临逻辑复用的问题.在React中实现逻辑复用通常有以下几种方式:Mixin.高阶组件(HOC).修饰器(decorator).Render Props.Ho ...

  8. React项目的最佳实践

    项目代码 从零开始简书项目 ​ 从我第一次接触vue这个框架已经过了快一年的时间,陪伴我从前端小白到前端工程师,前端时间也是使用了 ts+vue这样的组合写代码,明显感觉vue与ts似乎没有产生比较好 ...

  9. Vue2.0 keep-alive 组件的最佳实践

    1.基本用法 vue2.0提供了一个keep-alive组件用来缓存组件,避免多次加载相应的组件,减少性能消耗 <keep-alive> <component> <!-- ...

随机推荐

  1. css img换行之后有空隙

    这样的2个图片换行之后有空隙<img src="img/qiche.jpg" /> <br /> <img src="img/qiche.j ...

  2. NetworkManager 冲突

    今天看centos7的视频的时候发现视频里总是配置ip失败,明明什么都对的,没有错误 至少在逻辑上是没有的 情况发生 1.centos7会自动启动这个服务,NetworkManager服务,重启后ip ...

  3. execl列数据成等差递增递减

    如上图若想以10,20,30...这样递增: 1).首先需选中10,20所在的单元格,鼠标移至20所在的单元格右下角 2).此时会出现一个十字"十"符号,点击直向下拖动至某个地方, ...

  4. 换行符\n和回车符\r

    问题始于社区的一个帖子,楼主的问题如下: “在c语言中,对一个不知道大小的文件进行读操作,我用fread()将文件的内容先放到一个缓存区,然后将缓存区中的内容打印出来, 缓存区中的内容和文件中的内容不 ...

  5. JAVA并发编程学习笔记------对象的可见性及发布逸出

    一.非原子的64位操作: 当线程在没有同步的情况下读取变量时,可能会得到一个失效值,但至少这个值是由之前某个线程设置的值,而不是一个随机值,这种安全性保证被称为最低安全性.最低安全性适用于绝大多数变量 ...

  6. 02_Python基本数据类型

    一.什么是数据 数据是描述客观事物的字符(比如95,不同的语义可表示成绩或体重),是计算机可以操作的对象,能够被计算机识别并输入给计算机处理的符号集合. 数据不仅仅包含整形,还包括图像.音乐.视频等非 ...

  7. 2018Pycharm激活方法

    1.将"0.0.0.0 account.jetbrains.com"添加到hosts文件中 2.打开http://idea.lanyus.com/ 3.获取激活码,粘贴到第二个选项 ...

  8. 洛谷3月月赛 R1 Step! ZERO to ONE

    洛谷3月月赛 R1 Step! ZERO to ONE 普及组难度 290.25/310滚粗 t1 10分的日语翻译题....太难了不会... t2 真·普及组.略 注意长为1的情况 #include ...

  9. java设计模式在公众号的应用——我是一个快乐的单例

    终于可以休息了,寻一把躺椅,安置于庭院,携一壶好茶,品一番风轻云淡... 自由自在的呼吸,伸手即可触摸阳光的温度,此时此刻,我就是我,像一个单例. 想起『设计模式』,就像想起了很久很久以前的故事,今日 ...

  10. javascript 欺骗词法作用域

    如果词法作用域完全由写代码期间函数所声明的位置来定义,怎样才能在运行时来"修改"(也可以说欺骗)词法作用域呢?    JavaScript 中有两种机制来实现这个目的.社区普遍认为 ...