編寫react組件更優實踐
我最開始學習react的時候,看到過各種各樣編寫組件的方式,不同教程中提出的方法往往有很大不同。當時雖說react這個框架已經十分成熟,但是似乎還沒有一種公認正確的使用方法。過去幾年中,我們團隊編寫了很多react組件,我們對實現方法進行了不斷的優化,直到滿意。
本文介紹了我們在實踐中的***實踐方式,希望能對無論是初學者還是有經驗的開發者來說都有一定的幫助。
在我們開始之前,有幾點需要說明:
- 我們是用es6和es7語法
- 如果你不了解展示組件和容器組件的區別,可以先閱讀這篇文章
- 如果你有任何建議、問題或者反饋,可以給我們留言
Class Based Components (基于類的組件)
Class based components 有自己的state和方法。我們會盡可能謹慎的使用這些組件,但是他們有自己的使用場景。
接下來我們就一行一行來編寫組件。
導入CSS
- import React, { Component } from 'react'
- import { observer } from 'mobx-react'
- import ExpandableForm from './ExpandableForm'
- import './styles/ProfileContainer.css'
我很喜歡CSS in JS,但是它目前還是一種新的思想,成熟的解決方案還未產生。我們在每個組件中都導入了它的css文件。
譯者注:目前CSS in JS可以使用css modules方案來解決,webpack的css-loader已經提供了該功能
我們還用一個空行來區分自己的依賴。
譯者注:即第4、5行和第1、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。
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>
- }
(全文完)