最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

編寫React組件項(xiàng)目實(shí)踐分析

 更新時(shí)間:2018年03月04日 09:40:33   作者:Magic Studio  
本文通過(guò)實(shí)例給大家分享了編寫React組件項(xiàng)目實(shí)踐的全過(guò)程,對(duì)此有興趣的朋友可以參考下。

當(dāng)我剛開(kāi)始寫React的時(shí)候,我看過(guò)很多寫組件的方法。一百篇教程就有一百種寫法。雖然React本身已經(jīng)成熟了,但是如何使用它似乎還沒(méi)有一個(gè)“正確”的方法。所以我(作者)把我們團(tuán)隊(duì)這些年來(lái)總結(jié)的使用React的經(jīng)驗(yàn)總結(jié)在這里。希望這篇文字對(duì)你有用,不管你是初學(xué)者還是老手。

開(kāi)始前:

我們使用ES6、ES7語(yǔ)法如果你不是很清楚展示組件和容器組件的區(qū)別,建議您從閱讀這篇文章開(kāi)始如果您有任何的建議、疑問(wèn)都清在評(píng)論里留言 基于類的組件

現(xiàn)在開(kāi)發(fā)React組件一般都用的是基于類的組件。下面我們就來(lái)一行一樣的編寫我們的組件:

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

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

我很喜歡css in javascript。但是,這個(gè)寫樣式的方法還是太新了。所以我們?cè)诿總€(gè)組件里引入css文件。而且本地引入的import和全局的import會(huì)用一個(gè)空行來(lái)分割。

初始化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。更多相關(guān)可以看這里。但是我們選擇更加清晰的方法。
同時(shí),我們確保在類前面加上了export default。(譯者注:雖然這個(gè)在使用了redux的時(shí)候不一定對(duì))。

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是靜態(tài)屬性。盡可能在組件類的的前面定義,讓其他的開(kāi)發(fā)人員讀代碼的時(shí)候可以立刻注意到。他們可以起到文檔的作用。

如果你使用了React 15.3.0或者更高的版本,那么需要另外引入prop-types包,而不是使用React.PropTypes。更多內(nèi)容移步這里。

你所有的組件都應(yīng)該有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 })
 }

 // ...

}

在類組件里,當(dāng)你把方法傳遞給子組件的時(shí)候,需要確保他們被調(diào)用的時(shí)候使用的是正確的this。一般都會(huì)在傳給子組件的時(shí)候這么做:this.handleSubmit.bind(this)。

使用ES6的箭頭方法就簡(jiǎn)單多了。它會(huì)自動(dòng)維護(hù)正確的上下文(this)。

給setState傳入一個(gè)方法

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

this.setState({ expanded: !this.state.expanded });
setState其實(shí)是異步的!React為了提高性能,會(huì)把多次調(diào)用的setState放在一起調(diào)用。所以,調(diào)用了setState之后state不一定會(huì)立刻就發(fā)生改變。

所以,調(diào)用setState的時(shí)候,你不能依賴于當(dāng)前的state值。因?yàn)閕根本不知道它是值會(huì)是神馬。

解決方法:給setState傳入一個(gè)方法,把調(diào)用前的state值作為參數(shù)傳入這個(gè)方法。看看例子:

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的,每一個(gè)prop都應(yīng)該單獨(dú)占一行。就如上例一樣。要達(dá)到這個(gè)目標(biāo)最好的方法是使用一套工具:Prettier。

裝飾器(Decorator)

@observer
export default class ProfileContainer extends Component {

如果你了解某些庫(kù),比如mobx,你就可以使用上例的方式來(lái)修飾類組件。裝飾器就是把類組件作為一個(gè)參數(shù)傳入了一個(gè)方法。

裝飾器可以編寫更靈活、更有可讀性的組件。如果你不想用裝飾器,你可以這樣:

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是一個(gè)React組件的話,這樣自動(dòng)觸發(fā)它的重繪,不管其他的props是否發(fā)生了改變。

一致性檢驗(yàn)是React最消耗資源的部分。不要把額外的工作加到這里。處理上例中的問(wèn)題最好的方法是傳入一個(gè)類方法,這樣還會(huì)更加易讀,更容易調(diào)試。如:

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

方法組件

這類組件沒(méi)有state沒(méi)有props,也沒(méi)有方法。它們是純組件,包含了最少的引起變化的內(nèi)容。經(jīng)常使用它們。

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

我們?cè)诮M件的聲明之前就定義了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>
 )
}

我們的組件是一個(gè)方法。它的參數(shù)就是props。我們可以這樣擴(kuò)展這個(gè)組件:

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

現(xiàn)在我們也可以使用默認(rèn)參數(shù)來(lái)扮演默認(rèn)props的角色,這樣有很好的可讀性。如果expanded沒(méi)有定義,那么我們就把它設(shè)置為false。

但是,盡量避免使用如下的例子:

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

看起來(lái)很現(xiàn)代,但是這個(gè)方法是未命名的。

如果你的Babel配置正確,未命名的方法并不會(huì)是什么大問(wèn)題。但是,如果Babel有問(wèn)題的話,那么這個(gè)組件里的任何錯(cuò)誤都顯示為發(fā)生在 <>里的,這調(diào)試起來(lái)就非常麻煩了。

匿名方法也會(huì)引起Jest其他的問(wèn)題。由于會(huì)引起各種難以理解的問(wèn)題,而且也沒(méi)有什么實(shí)際的好處。我們推薦使用function,少使用const。

裝飾方法組件

由于方法組件沒(méi)法使用裝飾器,只能把它作為參數(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)

只能這樣處理: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)

條件判斷

某些情況下,你會(huì)做很多的條件判斷:

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

這么多層的條件判斷可不是什么好現(xiàn)象。

有第三方庫(kù)JSX-Control Statements可以解決這個(gè)問(wèn)題。但是與其增加一個(gè)依賴,還不如這樣來(lái)解決:

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

使用大括號(hào)包起來(lái)的IIFE,然后把你的if表達(dá)式都放進(jìn)去。返回你要返回的組件。

最后

再次,希望本文對(duì)你有用。如果你有什么好的意見(jiàn)或者建議的話請(qǐng)寫在下面的評(píng)論里。謝謝!

相關(guān)文章

  • React組件通信淺析

    React組件通信淺析

    這篇文章主要介紹了React組件通信,在開(kāi)發(fā)中組件通信是React中的一個(gè)重要的知識(shí)點(diǎn),本文通過(guò)實(shí)例代碼給大家講解react中常用的父子、跨組件通信的方法,需要的朋友可以參考下
    2022-12-12
  • React學(xué)習(xí)筆記之條件渲染(一)

    React學(xué)習(xí)筆記之條件渲染(一)

    條件渲染在React里就和js里的條件語(yǔ)句一樣。下面這篇文章主要給大家介紹了關(guān)于React學(xué)習(xí)記錄之條件渲染的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2017-07-07
  • react分頁(yè)顯示數(shù)據(jù)的方法

    react分頁(yè)顯示數(shù)據(jù)的方法

    分頁(yè)在很多地方都可以用到,本文主要實(shí)現(xiàn)了react分頁(yè)顯示,主要使用三個(gè)組件,父組件listBox、列表組件List、按鈕組件PageButton,感興趣的可以了解一下
    2021-08-08
  • 簡(jiǎn)單分析React中的EffectList

    簡(jiǎn)單分析React中的EffectList

    這篇文章主要簡(jiǎn)單分析了React中的EffectList,幫助大家更好的理解和學(xué)習(xí)使用React進(jìn)行前端開(kāi)發(fā),感興趣的朋友可以了解下
    2021-04-04
  • 解析React?ref?命令代替父子組件的數(shù)據(jù)傳遞問(wèn)題

    解析React?ref?命令代替父子組件的數(shù)據(jù)傳遞問(wèn)題

    這篇文章主要介紹了React?-?ref?命令為什么代替父子組件的數(shù)據(jù)傳遞,使用?ref?之后,我們不需要再進(jìn)行頻繁的父子傳遞了,子組件也可以有自己的私有狀態(tài)并且不會(huì)影響信息的正常需求,這是為什么呢?因?yàn)槲覀兪褂昧?ref?命令的話,ref是可以進(jìn)行狀態(tài)的傳輸
    2022-08-08
  • React中使用async validator進(jìn)行表單驗(yàn)證的實(shí)例代碼

    React中使用async validator進(jìn)行表單驗(yàn)證的實(shí)例代碼

    react上進(jìn)行表單驗(yàn)證是很繁瑣的,在這里使用async-validator處理起來(lái)就變的很方便了,接下來(lái)通過(guò)本文給大家介紹React中使用async validator進(jìn)行表單驗(yàn)證的方法,需要的朋友可以參考下
    2018-08-08
  • React實(shí)現(xiàn)createElement 和 cloneElement的區(qū)別

    React實(shí)現(xiàn)createElement 和 cloneElement的區(qū)別

    本文詳細(xì)介紹了React中React.createElement和React.cloneElement兩種方法的定義、用法、區(qū)別及適用場(chǎng)景,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-09-09
  • React進(jìn)行路由變化監(jiān)聽(tīng)的解決方案

    React進(jìn)行路由變化監(jiān)聽(tīng)的解決方案

    在現(xiàn)代單頁(yè)應(yīng)用(SPA)中,路由管理是至關(guān)重要的一部分,它不僅決定了用戶如何在頁(yè)面間切換,還直接影響到整個(gè)應(yīng)用的性能和用戶體驗(yàn),這些看似不起眼的問(wèn)題,往往會(huì)導(dǎo)致功能錯(cuò)亂和性能下降,本篇文章將深入探討在 React 中如何高效監(jiān)聽(tīng)路由變化,需要的朋友可以參考下
    2025-01-01
  • 詳解React如何使用??useReducer???高階鉤子來(lái)管理狀態(tài)

    詳解React如何使用??useReducer???高階鉤子來(lái)管理狀態(tài)

    useReducer是React中的一個(gè)鉤子,用于替代?useState來(lái)管理復(fù)雜的狀態(tài)邏輯,本文將詳細(xì)介紹如何在React中使用?useReducer高階鉤子來(lái)管理狀態(tài),感興趣的可以了解下
    2025-02-02
  • 在react配置使用less的完美方案

    在react配置使用less的完美方案

    由于 create-react-app 使用 webpack 作為其模塊打包器,你需要修改 webpack 的配置來(lái)支持 .less 文件,這篇文章主要介紹了在react配置使用less的完美方案,需要的朋友可以參考下
    2024-04-04

最新評(píng)論

云梦县| 昆明市| 连南| 连平县| 井冈山市| 双桥区| 揭西县| 平原县| 洛南县| 商城县| 大理市| 清涧县| 忻州市| 敦化市| 阳西县| 邛崃市| 绿春县| 肥乡县| 班玛县| 无极县| 镶黄旗| 保德县| 宽甸| 玛多县| 隆昌县| 玉林市| 巫溪县| 钟山县| 朝阳县| 盐池县| 陕西省| 冷水江市| 青岛市| 扎鲁特旗| 道真| 沧州市| 信宜市| 岫岩| 抚顺县| 四会市| 辽宁省|