编写react组件最佳实践

本文译自:https://engineering.musefind....css

图片描述

我最开始学习react的时候,看到过各类各样编写组件的方式,不一样教程中提出的方法每每有很大不一样。当时虽然说react这个框架已经十分红熟,可是彷佛尚未一种公认正确的使用方法。过去几年中,咱们团队编写了不少react组件,咱们对实现方法进行了不断的优化,直到满意。react

本文介绍了咱们在实践中的最佳实践方式,但愿能对不管是初学者仍是有经验的开发者来讲都有必定的帮助。webpack

在咱们开始以前,有几点须要说明:es6

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

Class Based Components (基于类的组件)

Class based components 有本身的state和方法。咱们会尽量谨慎的使用这些组件,可是他们有本身的使用场景。web

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

导入CSS

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

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

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

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

咱们还用一个空行来区分本身的依赖。闭包

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

初始化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,不过咱们更喜欢这种简洁的方式。咱们还会确保默认导出组件的class。app

propTypes 和 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'
  }

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

方法

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

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

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

constructor() {
    this.handleSubmit = this.handleSubmit.bind(this);
}

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

在上文的例子中,咱们是这么作的:

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

setState实际是异步执行的,react由于性能缘由会将state的变化整合,再一块儿处理,所以当setState被调用的时候,state并不必定会当即变化。

这意味着在调用setState的时候你不能依赖当前的state值——由于你不能确保setState真正被调用的时候state到底是什么。

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

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

解构props

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的组件来讲,应当像上述写法同样,将每一个属性解构出来,且每一个属性单独一行。

装饰器(Decorators)

@observer
export default class ProfileContainer extends Component {

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

若是你不想使用装饰器,能够按照以下方式来作:

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

闭包

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

<input
            type="text"
            value={model.name}
            // onChange={(e) => { model.name = e.target.value }}
            // ^ 不要这样写,按以下写法:
            onChange={this.handleChange}
            placeholder="Your Name"/>

缘由在于:每次父组件从新渲染时,都会建立一个新的函数,并传给input。

若是这个input是个react组件的话,这会致使不管该组件的其余属性是否变化,该组件都会从新render。

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

完整代码以下:

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

函数组件(Functional Components)

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

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,很是直观。咱们能够这么作是由于js的函数名提高机制。

Destructuring Props and defaultProps(解构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>
  )
}

咱们能够给参数设置默认值,做为defaultProps。若是expanded是undefined,就将其设置为false。(这种设置默认值的方式,对于对象类的入参很是有用,能够避免`can't read property XXXX of undefined的错误)

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

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

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

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

Wrapping

在函数组件中不能使用装饰器,咱们能够将其做为入参传给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 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)

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

有时候咱们须要在render中写不少的判断逻辑,如下这种写法是咱们应该要避免的:
图片描述

目前有一些库来解决这个问题,可是咱们没有引入其余依赖,而是采用了以下方式来解决:
图片描述
这里咱们采用当即执行函数的方式来解决问题,将if语句放到当即执行函数中,返回任何你想返回的。须要注意的是,当即执行函数会带来必定的性能问题,可是对于代码的可读性来讲,这个影响能够忽略。

一样的,当你只但愿在某种状况下渲染时,不要这么作:

{
  isTrue
   ? <p>True!</p>
   : <none/>
}

而应当这么作:

{
  isTrue && 
    <p>True!</p>
}

(全文完)

本文也同步在语雀,会持续记录个人学习及平常反思等内容,欢迎你们浏览关注~

相关文章
相关标签/搜索