如何成為react大神!!!
通過例項給大家分享了編寫React元件專案實踐的全過程,寫的十分的全面細緻,具有一定的參考價值,對此有需要的朋友可以參考學習下。如有不足之處,歡迎批評指正。
開始前:
我們使用ES6、ES7語法如果你不是很清楚展示元件和容器元件的區別,建議您從閱讀這篇文章開始如果您有任何的建議、疑問都清在評論裡留言 基於類的元件
現在開發React元件一般都用的是基於類的元件。下面我們就來一行一樣的編寫我們的元件:
import React, { Component } from 'react'; import { observer } from 'mobx-react'; import ExpandableForm from './ExpandableForm'; import './styles/ProfileContainer.css';
其實我很喜歡css in javascript。但是,這個寫樣式的方法還是太新了。所以我們在每個元件裡引入css檔案。而且本地引入的import和全域性的import會用一個空行來分割。
初始化State import React, { Component } from 'react' import { observer } from 'mobx-react' import ExpandableForm from './ExpandableForm' import './styles/ProfileContainer.css' //歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860 export default class ProfileContainer extends Component { state = { expanded: false }
可以使用了老方法在constructor裡初始化state。更多相關可以看這裡。但是我們選擇更加清晰的方法。
同時,我們確保在類前面加上了export default。(譯者注:雖然這個在使用了redux的時候不一定對)。
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' } // ... }//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
propTypes和defaultProps是靜態屬性。儘可能在元件類的的前面定義,讓其他的開發人員讀程式碼的時候可以立刻注意到。他們可以起到文件的作用。
如果你使用了React 15.3.0或者更高的版本,那麼需要另外引入prop-types包,而不是使用React.PropTypes。更多內容移步這裡。
你所有的元件都應該有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 })
}
// ...
}//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
在類元件裡,當你把方法傳遞給子元件的時候,需要確保他們被呼叫的時候使用的是正確的this。一般都會在傳給子元件的時候這麼做:this.handleSubmit.bind(this)。
使用ES6的箭頭方法就簡單多了。它會自動維護正確的上下文(this)。
給setState傳入一個方法
在上面的例子裡有這麼一行:
this.setState({ expanded: !this.state.expanded });
setState其實是非同步的!React為了提高效能,會把多次呼叫的setState放在一起呼叫。所以,呼叫了setState之後state不一定會立刻就發生改變。
所以,呼叫setState的時候,你不能依賴於當前的state值。因為i根本不知道它是值會是神馬。
解決方法:給setState傳入一個方法,把呼叫前的state值作為引數傳入這個方法。看看例子:
this.setState(prevState => ({ expanded: !prevState.expanded }))
拆解元件
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 }
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
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 }))
}
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
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的,每一個prop都應該單獨佔一行。就如上例一樣。要達到這個目標最好的方法是使用一套工具:Prettier。
裝飾器(Decorator)
@observer
export default class ProfileContainer extends Component {
如果你瞭解某些庫,比如mobx,你就可以使用上例的方式來修飾類元件。裝飾器就是把類元件作為一個引數傳入了一個方法。
裝飾器可以編寫更靈活、更有可讀性的元件。如果你不想用裝飾器,你可以這樣:
class ProfileContainer extends Component {
// Component code
}//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
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是一個React元件的話,這樣自動觸發它的重繪,不管其他的props是否發生了改變。
一致性檢驗是React最消耗資源的部分。不要把額外的工作加到這裡。處理上例中的問題最好的方法是傳入一個類方法,這樣還會更加易讀,更容易除錯。如:
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'
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
// 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'
}
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
// 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>//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
</ExpandableForm>
)
}
}
方法元件
這類元件沒有state沒有props,也沒有方法。它們是純元件,包含了最少的引起變化的內容。經常使用它們。
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
}//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
// Component declaration
我們在元件的宣告之前就定義了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
}
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
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'
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
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 (//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
<form style={formStyle} onSubmit={onSubmit}>
{children}
<button onClick={onExpand}>Expand</button>
</form>
)
}
現在我們也可以使用預設引數來扮演預設props的角色,這樣有很好的可讀性。如果expanded沒有定義,那麼我們就把它設定為false。
但是,儘量避免使用如下的例子:
const ExpandableForm = ({ onExpand, expanded, children }) => {
看起來很現代,但是這個方法是未命名的。
如果你的Babel配置正確,未命名的方法並不會是什麼大問題。但是,如果Babel有問題的話,那麼這個元件裡的任何錯誤都顯示為發生在 <>裡的,這除錯起來就非常麻煩了。
匿名方法也會引起Jest其他的問題。由於會引起各種難以理解的問題,而且也沒有什麼實際的好處。我們推薦使用function,少使用const。
裝飾方法元件
由於方法元件沒法使用裝飾器,只能把它作為引數傳入別的方法裡。
import React from 'react'
import { observer } from 'mobx-react'
import { func, bool } from 'prop-types'
import './styles/Form.css'
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
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>//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
)
}
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'
//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
// 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)
條件判斷
某些情況下,你會做很多的條件判斷:
<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>
}//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
</div>
這麼多層的條件判斷可不是什麼好現象。
有第三方庫JSX-Control Statements可以解決這個問題。但是與其增加一個依賴,還不如這樣來解決:
<div id="lb-footer">
{//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
(() => {
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>
使用大括號包起來的IIFE,然後把你的if表示式都放進去。返回你要返回的元件。
結語
感謝您的觀看,如有不足之處,歡迎批評指正。
本次給大家推薦一個免費的學習群,裡面概括移動應用網站開發,css,html,webpack,vue node angular以及面試資源等。
對web開發技術感興趣的同學,歡迎加入Q群:864305860,不管你是小白還是大牛我都歡迎,還有大牛整理的一套高效率學習路線和教程與您免費分享,同時每天更新視訊資料。
最後,祝大家早日學有所成,拿到滿意offer,快速升職加薪,走上人生巔峰。