日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯網營銷解決方案
編寫react組件更優(yōu)實踐

我最開始學習react的時候,看到過各種各樣編寫組件的方式,不同教程中提出的方法往往有很大不同。當時雖說react這個框架已經十分成熟,但是似乎還沒有一種公認正確的使用方法。過去幾年中,我們團隊編寫了很多react組件,我們對實現方法進行了不斷的優(yōu)化,直到滿意。

本文介紹了我們在實踐中的***實踐方式,希望能對無論是初學者還是有經驗的開發(fā)者來說都有一定的幫助。

在我們開始之前,有幾點需要說明:

  • 我們是用es6和es7語法
  • 如果你不了解展示組件和容器組件的區(qū)別,可以先閱讀這篇文章
  • 如果你有任何建議、問題或者反饋,可以給我們留言

Class Based Components (基于類的組件)

Class based components 有自己的state和方法。我們會盡可能謹慎的使用這些組件,但是他們有自己的使用場景。

接下來我們就一行一行來編寫組件。

導入CSS

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

我很喜歡CSS in JS,但是它目前還是一種新的思想,成熟的解決方案還未產生。我們在每個組件中都導入了它的css文件。

譯者注:目前CSS in JS可以使用css modules方案來解決,webpack的css-loader已經提供了該功能

我們還用一個空行來區(qū)分自己的依賴。

譯者注:即第4、5行和第1、2行中間會單獨加行空行。

初始化state

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

你也可以在constructor中初始化state,不過我們更喜歡這種簡潔的方式。我們還會確保默認導出組件的class。

propTypes 和 defaultProps

 
 
 
 
  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import { string, object } from 'prop-types' 
  6.  
  7. import ExpandableForm from './ExpandableForm' 
  8.  
  9. import './styles/ProfileContainer.css' 
  10.  
  11. export default class ProfileContainer extends Component { 
  12.  
  13. state = { expanded: false } 
  14.  
  15. static propTypes = { 
  16.  
  17. model: object.isRequired, 
  18.  
  19. title: string 
  20.  
  21.  
  22. static defaultProps = { 
  23.  
  24. model: { 
  25.  
  26. id: 0 
  27.  
  28. }, 
  29.  
  30. title: 'Your Name' 
  31.  
  32. }  

propTypes和defaultProps是靜態(tài)屬性,應該盡可能在代碼的頂部聲明。這兩個屬性起著文檔的作用,應該能夠使閱讀代碼的開發(fā)者一眼就能夠看到。如果你正在使用react 15.3.0或者更高的版本,使用prop-types,而不是React.PropTypes。你的所有組件,都應該有propTypes屬性。

方法

 
 
 
 
  1. import React, { Component } from 'react' 
  2.  
  3. import { observer } from 'mobx-react' 
  4.  
  5. import { string, object } from 'prop-types' 
  6.  
  7. import ExpandableForm from './ExpandableForm' 
  8.  
  9. import './styles/ProfileContainer.css' 
  10.  
  11. export default class ProfileContainer extends Component { 
  12.  
  13. state = { expanded: false } 
  14.  
  15. static propTypes = { 
  16.  
  17. model: object.isRequired, 
  18.  
  19. title: string 
  20.  
  21.  
  22. static defaultProps = { 
  23.  
  24. model: { 
  25.  
  26. id: 0 
  27.  
  28. }, 
  29.  
  30. title: 'Your Name' 
  31.  
  32.  
  33. handleSubmit = (e) => { 
  34.  
  35. e.preventDefault() 
  36.  
  37. this.props.model.save() 
  38.  
  39.  
  40. handleNameChange = (e) => { 
  41.  
  42. this.props.model.changeName(e.target.value) 
  43.  
  44.  
  45. handleExpand = (e) => { 
  46.  
  47. e.preventDefault() 
  48.  
  49. this.setState({ expanded: !this.state.expanded }) 
  50.  
  51. }  

使用class components,當你向子組件傳遞方法的時候,需要確保這些方法被調用時有正確的this值。通常會在向子組件傳遞時使用this.handleSubmit.bind(this)來實現。當然,使用es6的箭頭函數寫法更加簡潔。

譯者注:也可以在constructor中完成方法的上下文的綁定:

 
 
 
 
  1. constructor() { 
  2.  
  3. this.handleSubmit = this.handleSubmit.bind(this); 
  4.  
  5. }  

給setState傳入一個函數作為參數(passing setState a Function)

在上文的例子中,我們是這么做的:

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

setState實際是異步執(zhí)行的,react因為性能原因會將state的變化整合,再一起處理,因此當setState被調用的時候,state并不一定會立即變化。

這意味著在調用setState的時候你不能依賴當前的state值——因為你不能確保setState真正被調用的時候state究竟是什么。

解決方案就是給setState傳入一個方法,該方法接收上一次的state作為參數。

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

解構props

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

    {title}

     
  46.           
  47.             type="text" 
  48.             value={model.name} 
  49.             onChange={this.handleNameChange} 
  50.             placeholder="Your Name"/> 
  51.         
 
  •        
  •     ) 
  •   } 
  • }  
  • 對于有很多props的組件來說,應當像上述寫法一樣,將每個屬性解構出來,且每個屬性單獨一行。

    裝飾器(Decorators)

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

    如果你正在使用類似于mobx的狀態(tài)管理器,你可以按照上述方式描述你的組件。這種寫法與將組件作為參數傳遞給一個函數效果是一樣的。裝飾器(decorators)是一種非常靈活和易讀的定義組件功能的方式。我們使用mobx和mobx-models來結合裝飾器進行使用。

    如果你不想使用裝飾器,可以按照如下方式來做:

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

    閉包

    避免向子組件傳入閉包,如下:

     
     
     
     
    1.             type="text" 
    2.             value={model.name} 
    3.             // onChange={(e) => { model.name = e.target.value }} 
    4.             // ^ 不要這樣寫,按如下寫法: 
    5.             onChange={this.handleChange} 
    6.             placeholder="Your Name"/>  

    原因在于:每次父組件重新渲染時,都會創(chuàng)建一個新的函數,并傳給input。

    如果這個input是個react組件的話,這會導致無論該組件的其他屬性是否變化,該組件都會重新render。

    而且,采用將父組件的方法傳入的方式也會使得代碼更易讀,方便調試,同時也容易修改。

    完整代碼如下:

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

      {title}

       
    57.           
    58.             type="text" 
    59.             value={model.name} 
    60.             // onChange={(e) => { model.name = e.target.value }} 
    61.             // Avoid creating new closures in the render method- use methods like below 
    62.             onChange={this.handleNameChange} 
    63.             placeholder="Your Name"/> 
    64.         
     
  •          
  •     ) 
  •   } 
  • }  
  • 函數組件(Functional Components)

    這些組件沒有state和方法。它們是純凈的,非常容易定位問題,可以盡可能多的使用這些組件。

    propTypes

     
     
     
     
    1. import React from 'react' 
    2. import { observer } from 'mobx-react' 
    3. import { func, bool } from 'prop-types' 
    4.  
    5. import './styles/Form.css' 
    6. ExpandableForm.propTypes = { 
    7.   onSubmit: func.isRequired, 
    8.   expanded: bool 
    9. // Component declaration  

    這里我們在組件聲明之前就定義了propTypes,非常直觀。我們可以這么做是因為js的函數名提升機制。

    Destructuring Props and defaultProps(解構props和defaultProps)

     
     
     
     
    1. import React from 'react' 
    2. import { observer } from 'mobx-react' 
    3. import { func, bool } from 'prop-types' 
    4.  
    5. import './styles/Form.css' 
    6. ExpandableForm.propTypes = { 
    7.   onSubmit: func.isRequired, 
    8.   expanded: bool, 
    9.   onExpand: func.isRequired 
    10. function ExpandableForm(props) { 
    11.   const formStyle = props.expanded ? {height: 'auto'} : {height: 0} 
    12.   return ( 
    13.      
    14.       {props.children} 
    15.       Expand 
    16.      
    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. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
    10.   const formStyle = expanded ? {height: 'auto'} : {height: 0} 
    11.   return ( 
    12.      
    13.       {children} 
    14.       Expand 
    15.      
    16.   ) 
    17. }  

    我們可以給參數設置默認值,作為defaultProps。如果expanded是undefined,就將其設置為false。(這種設置默認值的方式,對于對象類的入參非常有用,可以避免`can't read property XXXX of undefined的錯誤)

    不要使用es6箭頭函數的寫法:

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

    這種寫法中,函數實際是匿名函數。如果正確地使用了babel則不成問題,但是如果沒有,運行時就會導致一些錯誤,非常不方便調試。

    另外,在Jest,一個react的測試庫,中使用匿名函數也會導致一些問題。由于使用匿名函數可能會出現一些潛在的問題,我們推薦使用function,而不是const。

    Wrapping

    在函數組件中不能使用裝飾器,我們可以將其作為入參傳給observer函數

     
     
     
     
    1. import React from 'react' 
    2. import { observer } from 'mobx-react' 
    3. import { func, bool } from 'prop-types' 
    4.  
    5. import './styles/Form.css' 
    6. ExpandableForm.propTypes = { 
    7.   onSubmit: func.isRequired, 
    8.   expanded: bool, 
    9.   onExpand: func.isRequired 
    10. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
    11.   const formStyle = expanded ? {height: 'auto'} : {height: 0} 
    12.   return ( 
    13.      
    14.       {children} 
    15.       Expand 
    16.      
    17.   ) 
    18. 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.  
    7. // Declare propTypes here, before the component (taking advantage of JS function hoisting) 
    8. // You want these to be as visible as possible 
    9. ExpandableForm.propTypes = { 
    10.   onSubmit: func.isRequired, 
    11.   expanded: bool, 
    12.   onExpand: func.isRequired 
    13.  
    14. // Destructure props like so, and use default arguments as a way of setting defaultProps 
    15. function ExpandableForm({ onExpand, expanded = false, children, onSubmit }) { 
    16.   const formStyle = expanded ? { height: 'auto' } : { height: 0 } 
    17.   return ( 
    18.      
    19.       {children} 
    20.       Expand 
    21.      
    22.   ) 
    23.  
    24. // Wrap the component instead of decorating it 
    25. export default observer(ExpandableForm)  

    在JSX中使用條件判斷(Conditionals in JSX)

    有時候我們需要在render中寫很多的判斷邏輯,以下這種寫法是我們應該要避免的:

    目前有一些庫來解決這個問題,但是我們沒有引入其他依賴,而是采用了如下方式來解決:

    這里我們采用立即執(zhí)行函數的方式來解決問題,將if語句放到立即執(zhí)行函數中,返回任何你想返回的。需要注意的是,立即執(zhí)行函數會帶來一定的性能問題,但是對于代碼的可讀性來說,這個影響可以忽略。

    同樣的,當你只希望在某種情況下渲染時,不要這么做:

     
     
     
     
    1.   isTrue 
    2.    ? 

      True!

       
    3.    :  
    4. }  

    而應當這么做:

     
     
     
     
    1.  
    2. isTrue && 
    3.  
    4. True!

       
    5.  
    6. }  

    (全文完)


    本文名稱:編寫react組件更優(yōu)實踐
    路徑分享:http://www.5511xx.com/article/dhiiepp.html