編寫react組件更優(yōu)實(shí)踐
我最開始學(xué)習(xí)react的時(shí)候,看到過各種各樣編寫組件的方式,不同教程中提出的方法往往有很大不同。當(dāng)時(shí)雖說react這個(gè)框架已經(jīng)十分成熟,但是似乎還沒有一種公認(rèn)正確的使用方法。過去幾年中,我們團(tuán)隊(duì)編寫了很多react組件,我們對(duì)實(shí)現(xiàn)方法進(jìn)行了不斷的優(yōu)化,直到滿意。
本文介紹了我們在實(shí)踐中的***實(shí)踐方式,希望能對(duì)無論是初學(xué)者還是有經(jīng)驗(yàn)的開發(fā)者來說都有一定的幫助。
在我們開始之前,有幾點(diǎn)需要說明:
- 我們是用es6和es7語法
- 如果你不了解展示組件和容器組件的區(qū)別,可以先閱讀這篇文章
- 如果你有任何建議、問題或者反饋,可以給我們留言
Class Based Components (基于類的組件)
Class based components 有自己的state和方法。我們會(huì)盡可能謹(jǐn)慎的使用這些組件,但是他們有自己的使用場景。
接下來我們就一行一行來編寫組件。
導(dǎo)入CSS
- import React, { Component } from 'react'
- import { observer } from 'mobx-react'
- import ExpandableForm from './ExpandableForm'
- import './styles/ProfileContainer.css'
我很喜歡CSS in JS,但是它目前還是一種新的思想,成熟的解決方案還未產(chǎn)生。我們在每個(gè)組件中都導(dǎo)入了它的css文件。
譯者注:目前CSS in JS可以使用css modules方案來解決,webpack的css-loader已經(jīng)提供了該功能
我們還用一個(gè)空行來區(qū)分自己的依賴。
譯者注:即第4、5行和第1、2行中間會(huì)單獨(dú)加行空行。
初始化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,不過我們更喜歡這種簡潔的方式。我們還會(huì)確保默認(rèn)導(dǎo)出組件的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是靜態(tài)屬性,應(yīng)該盡可能在代碼的頂部聲明。這兩個(gè)屬性起著文檔的作用,應(yīng)該能夠使閱讀代碼的開發(fā)者一眼就能夠看到。如果你正在使用react 15.3.0或者更高的版本,使用prop-types,而不是React.PropTypes。你的所有組件,都應(yīng)該有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,當(dāng)你向子組件傳遞方法的時(shí)候,需要確保這些方法被調(diào)用時(shí)有正確的this值。通常會(huì)在向子組件傳遞時(shí)使用this.handleSubmit.bind(this)來實(shí)現(xiàn)。當(dāng)然,使用es6的箭頭函數(shù)寫法更加簡潔。
譯者注:也可以在constructor中完成方法的上下文的綁定:
- constructor() {
- this.handleSubmit = this.handleSubmit.bind(this);
- }
給setState傳入一個(gè)函數(shù)作為參數(shù)(passing setState a Function)
在上文的例子中,我們是這么做的:
- this.setState({ expanded: !this.state.expanded })
setState實(shí)際是異步執(zhí)行的,react因?yàn)樾阅茉驎?huì)將state的變化整合,再一起處理,因此當(dāng)setState被調(diào)用的時(shí)候,state并不一定會(huì)立即變化。
這意味著在調(diào)用setState的時(shí)候你不能依賴當(dāng)前的state值——因?yàn)槟悴荒艽_保setState真正被調(diào)用的時(shí)候state究竟是什么。
解決方案就是給setState傳入一個(gè)方法,該方法接收上一次的state作為參數(shù)。
this.setState(prevState => ({ expanded: !prevState.expanded })
解構(gòu)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>
- )
- }
- }
對(duì)于有很多props的組件來說,應(yīng)當(dāng)像上述寫法一樣,將每個(gè)屬性解構(gòu)出來,且每個(gè)屬性單獨(dú)一行。
裝飾器(Decorators)
- @observer
- export default class ProfileContainer extends Component {
如果你正在使用類似于mobx的狀態(tài)管理器,你可以按照上述方式描述你的組件。這種寫法與將組件作為參數(shù)傳遞給一個(gè)函數(shù)效果是一樣的。裝飾器(decorators)是一種非常靈活和易讀的定義組件功能的方式。我們使用mobx和mobx-models來結(jié)合裝飾器進(jìn)行使用。
如果你不想使用裝飾器,可以按照如下方式來做:
- 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"/>
原因在于:每次父組件重新渲染時(shí),都會(huì)創(chuàng)建一個(gè)新的函數(shù),并傳給input。
如果這個(gè)input是個(gè)react組件的話,這會(huì)導(dǎo)致無論該組件的其他屬性是否變化,該組件都會(huì)重新render。
而且,采用將父組件的方法傳入的方式也會(huì)使得代碼更易讀,方便調(diào)試,同時(shí)也容易修改。
完整代碼如下:
- 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>
- )
- }
- }
函數(shù)組件(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,非常直觀。我們可以這么做是因?yàn)閖s的函數(shù)名提升機(jī)制。
Destructuring Props and defaultProps(解構(gòu)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>
- )
- }
我們的組件是一個(gè)函數(shù),props作為函數(shù)的入?yún)⒈粋鬟f進(jìn)來。我們可以按照如下方式對(duì)組件進(jìn)行擴(kuò)展:
- 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>
- )
- }
我們可以給參數(shù)設(shè)置默認(rèn)值,作為defaultProps。如果expanded是undefined,就將其設(shè)置為false。(這種設(shè)置默認(rèn)值的方式,對(duì)于對(duì)象類的入?yún)⒎浅S杏?,可以避免`can't read property XXXX of undefined的錯(cuò)誤)
不要使用es6箭頭函數(shù)的寫法:
- const ExpandableForm = ({ onExpand, expanded, children }) => {
這種寫法中,函數(shù)實(shí)際是匿名函數(shù)。如果正確地使用了babel則不成問題,但是如果沒有,運(yùn)行時(shí)就會(huì)導(dǎo)致一些錯(cuò)誤,非常不方便調(diào)試。
另外,在Jest,一個(gè)react的測試庫,中使用匿名函數(shù)也會(huì)導(dǎo)致一些問題。由于使用匿名函數(shù)可能會(huì)出現(xiàn)一些潛在的問題,我們推薦使用function,而不是const。
Wrapping
在函數(shù)組件中不能使用裝飾器,我們可以將其作為入?yún)鹘oobserver函數(shù)
- 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)
有時(shí)候我們需要在render中寫很多的判斷邏輯,以下這種寫法是我們應(yīng)該要避免的:
目前有一些庫來解決這個(gè)問題,但是我們沒有引入其他依賴,而是采用了如下方式來解決:
這里我們采用立即執(zhí)行函數(shù)的方式來解決問題,將if語句放到立即執(zhí)行函數(shù)中,返回任何你想返回的。需要注意的是,立即執(zhí)行函數(shù)會(huì)帶來一定的性能問題,但是對(duì)于代碼的可讀性來說,這個(gè)影響可以忽略。
同樣的,當(dāng)你只希望在某種情況下渲染時(shí),不要這么做:
- {
- isTrue
- ? <p>True!</p>
- : <none/>
- }
而應(yīng)當(dāng)這么做:
- {
- isTrue &&
- <p>True!</p>
- }
(全文完)