当我刚开始写React的时候,我看过很多写组件的方法。一百篇教程就有一百种写法。虽然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'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' } // ...}
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 }) } // ...}
新闻热点
疑难解答
图片精选