當我剛開始寫React的時候,我看過很多寫組件的方法。一百篇教程就有一百種寫法。雖然React本身已經(jīng)成熟了,但是如何使用它似乎還沒有一個“正確”的方法。所以我(作者)把我們團隊這些年來總結(jié)的使用React的經(jīng)驗總結(jié)在這里。希望這篇文字對你有用,不管你是初學(xué)者還是老手。
我們使用ES6、ES7語法如果你不是很清楚展示組件和容器組件的區(qū)別,建議您從閱讀這篇文章開始如果您有任何的建議、疑問都清在評論里留言 基于類的組件
現(xiàn)在開發(fā)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'export default class ProfileContainer extends Component { state = { expanded: false }您可以使用了老方法在constructor里初始化state。更多相關(guān)可以看這里。但是我們選擇更加清晰的方法。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' } // ...}propTypes和defaultProps是靜態(tài)屬性。盡可能在組件類的的前面定義,讓其他的開發(fā)人員讀代碼的時候可以立刻注意到。他們可以起到文檔的作用。
如果你使用了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 }) } // ...}
新聞熱點
疑難解答
圖片精選