编写React组件的最佳实践

此文翻译自这里javascript

当我刚开始写React的时候,我看过不少写组件的方法。一百篇教程就有一百种写法。虽然React自己已经成熟了,可是如何使用它彷佛尚未一个“正确”的方法。因此我(做者)把咱们团队这些年来总结的使用React的经验总结在这里。但愿这篇文字对你有用,无论你是初学者仍是老手。css

开始前:java

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

基于类的组件

如今开发React组件通常都用的是基于类的组件。下面咱们就来一行同样的编写咱们的组件:react

import React, { Component } from 'react';
import { observer } from 'mobx-react';

import ExpandableForm from './ExpandableForm';
import './styles/ProfileContainer.css';

我很喜欢css in javascript。可是,这个写样式的方法仍是太新了。因此咱们在每一个组件里引入css文件。并且本地引入的import和全局的import会用一个空行来分割。git

初始化State

import React, { Component } from 'react'
import { observer } from 'mobx-react'

import ExpandableForm from './ExpandableForm'
import './styles/ProfileContainer.css'

export default class ProfileContainer extends Component {
  state = { expanded: false }

您可使用了老方法在constructor里初始化state。更多相关能够看这里。可是咱们选择更加清晰的方法。
同时,咱们确保在类前面加上了export default。(译者注:虽然这个在使用了redux的时候不必定对)。es6

propTypes and defaultProps

import React, { Component } from 'react'
import { observer } from 'mobx-react'
import { string, object } from 'prop-types'

import ExpandableForm from './ExpandableForm'
import './styles/ProfileContainer.css'

export default class ProfileContainer extends Component {
  state = { expanded: false }
 
  static propTypes = {
    model: object.isRequired,
    title: string
  }
 
  static defaultProps = {
    model: {
      id: 0
    },
    title: 'Your Name'
  }

  // ...
}

propTypesdefaultProps是静态属性。尽量在组件类的的前面定义,让其余的开发人员读代码的时候能够马上注意到。他们能够起到文档的做用。github

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

你全部的组件都应该有prop types闭包

方法

import React, { Component } from 'react'
import { observer } from 'mobx-react'
import { string, object } from 'prop-types'

import ExpandableForm from './ExpandableForm'
import './styles/ProfileContainer.css'

export default class ProfileContainer extends Component {
  state = { expanded: false }
 
  static propTypes = {
    model: object.isRequired,
    title: string
  }
 
  static defaultProps = {
    model: {
      id: 0
    },
    title: 'Your Name'
  }
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.model.save()
  }
  
  handleNameChange = (e) => {
    this.props.model.changeName(e.target.value)
  }
  
  handleExpand = (e) => {
    e.preventDefault()
    this.setState({ expanded: !this.state.expanded })
  }

  // ...

}

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

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

给setState传入一个方法

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

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

setState实际上是异步的!React为了提升性能,会把屡次调用的setState放在一块儿调用。因此,调用了setState以后state不必定会马上就发生改变。

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

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

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

感谢Austin Wood的帮助。

拆解组件

import React, { Component } from 'react'
import { observer } from 'mobx-react'

import { string, object } from 'prop-types'
import ExpandableForm from './ExpandableForm'
import './styles/ProfileContainer.css'

export default class ProfileContainer extends Component {
  state = { expanded: false }
 
  static propTypes = {
    model: object.isRequired,
    title: string
  }
 
  static defaultProps = {
    model: {
      id: 0
    },
    title: 'Your Name'
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.model.save()
  }
  
  handleNameChange = (e) => {
    this.props.model.changeName(e.target.value)
  }
  
  handleExpand = (e) => {
    e.preventDefault()
    this.setState(prevState => ({ expanded: !prevState.expanded }))
  }
  
  render() {
    const {
      model,
      title
    } = this.props
    return ( 
      <ExpandableForm 
        onSubmit={this.handleSubmit} 
        expanded={this.state.expanded} 
        onExpand={this.handleExpand}>
        <div>
          <h1>{title}</h1>
          <input
            type="text"
            value={model.name}
            onChange={this.handleNameChange}
            placeholder="Your Name"/>
        </div>
      </ExpandableForm>
    )
  }
}

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

装饰器(Decorator)

@observer
export default class ProfileContainer extends Component {

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

装饰器能够编写更灵活、更有可读性的组件。若是你不想用装饰器,你能够这样:

class ProfileContainer extends Component {
  // Component code
}
export default observer(ProfileContainer)

闭包

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

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

注意:若是input是一个React组件的话,这样自动触发它的重绘,无论其余的props是否发生了改变。

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

import React, { Component } from 'react'
import { observer } from 'mobx-react'
import { string, object } from 'prop-types'
// Separate local imports from dependencies
import ExpandableForm from './ExpandableForm'
import './styles/ProfileContainer.css'

// Use decorators if needed
@observer
export default class ProfileContainer extends Component {
  state = { expanded: false }
  // Initialize state here (ES7) or in a constructor method (ES6)
 
  // Declare propTypes as static properties as early as possible
  static propTypes = {
    model: object.isRequired,
    title: string
  }

  // Default props below propTypes
  static defaultProps = {
    model: {
      id: 0
    },
    title: 'Your Name'
  }

  // Use fat arrow functions for methods to preserve context (this will thus be the component instance)
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.model.save()
  }
  
  handleNameChange = (e) => {
    this.props.model.name = e.target.value
  }
  
  handleExpand = (e) => {
    e.preventDefault()
    this.setState(prevState => ({ expanded: !prevState.expanded }))
  }
  
  render() {
    // Destructure props for readability
    const {
      model,
      title
    } = this.props
    return ( 
      <ExpandableForm 
        onSubmit={this.handleSubmit} 
        expanded={this.state.expanded} 
        onExpand={this.handleExpand}>
        // Newline props if there are more than two
        <div>
          <h1>{title}</h1>
          <input
            type="text"
            value={model.name}
            // onChange={(e) => { model.name = e.target.value }}
            // Avoid creating new closures in the render method- use methods like below
            onChange={this.handleNameChange}
            placeholder="Your Name"/>
        </div>
      </ExpandableForm>
    )
  }
}

方法组件

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

propTypes

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

咱们在组件的声明以前就定义了propTypes

分解Props和defaultProps

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(props) {
  const formStyle = props.expanded ? {height: 'auto'} : {height: 0}
  return (
    <form style={formStyle} onSubmit={props.onSubmit}>
      {props.children}
      <button onClick={props.onExpand}>Expand</button>
    </form>
  )
}

咱们的组件是一个方法。它的参数就是props。咱们能够这样扩展这个组件:

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

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

可是,尽可能避免使用以下的例子:

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

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

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

匿名方法也会引发Jest其余的问题。因为会引发各类难以理解的问题,并且也没有什么实际的好处。咱们推荐使用function,少使用const

装饰方法组件

因为方法组件无法使用装饰器,只能把它做为参数传入别的方法里。

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)

只能这样处理: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 of JS function hoisting)
// You want these to be as visible as possible
ExpandableForm.propTypes = {
  onSubmit: func.isRequired,
  expanded: bool,
  onExpand: func.isRequired
}

// Destructure props like so, and use default arguments as a way of setting defaultProps
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>
  )
}

// Wrap the component instead of decorating it
export default observer(ExpandableForm)

条件判断

某些状况下,你会作不少的条件判断:

<div id="lb-footer">
  {props.downloadMode && currentImage && !currentImage.video && currentImage.blogText
  ? !currentImage.submitted && !currentImage.posted
  ? <p>Please contact us for content usage</p>
    : currentImage && currentImage.selected
      ? <button onClick={props.onSelectImage} className="btn btn-selected">Deselect</button>
      : currentImage && currentImage.submitted
        ? <button className="btn btn-submitted" disabled>Submitted</button>
        : currentImage && currentImage.posted
          ? <button className="btn btn-posted" disabled>Posted</button>
          : <button onClick={props.onSelectImage} className="btn btn-unselected">Select post</button>
  }
</div>

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

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

<div id="lb-footer">
  {
    (() => {
      if(downloadMode && !videoSrc) {
        if(isApproved && isPosted) {
          return <p>Right click image and select "Save Image As.." to download</p>
        } else {
          return <p>Please contact us for content usage</p>
        }
      }

      // ...
    })()
  }
</div>

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

最后

再次,但愿本文对你有用。若是你有什么好的意见或者建议的话请写在下面的评论里。谢谢!

相关文章
相关标签/搜索