blog
blog copied to clipboard
React组件编码规范化
1.UI组件和container组件
UI组件是构成前端界面的基础单元,它们不涉及业务逻辑,无生命周期函数,只负责单纯的渲染,所有数据都通过 props 传入。
UI组件分为两种情况,有状态组件和无状态组件:
- 如果是无状态组件,则使用纯函数,我们大部分的UI组件都是这种纯函数。
// bad (relying on function name inference is discouraged)
const Listing = ({ hello }) => (
<div>{hello}</div>
);
// good
function Listing({ hello }) {
return <div>{hello}</div>;
}
- 如果模块有内部状态或者是refs, 推荐使用 class extends React.Component
// bad
const Listing = React.createClass({
// ...
render() {
return <div>{this.state.hello}</div>;
}
});
// good
class Listing extends React.Component {
// ...
render() {
return <div>{this.state.hello}</div>;
}
}
2. components导出默认模块
export { default as XScroll } from './XScroll';
export { default as TypeList } from './TypeList';
3.总是在Refs里使用回调函数
// bad
<Foo
ref="myRef"
/>
// good
<Foo
ref={(ref) => { this.myRef = ref; }}
/>
4.this.props.children
class NotesList extends React.Component{
render() {
return (
<ol>
{
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
}
</ol>
);
}
}
ReactDOM.render(
<NotesList>
<span>hello</span>
<span>world</span>
</NotesList>,
document.getElementById('example')
);
- 使用 React.Children.map 来遍历组件子节点
可以避免 this.props.children 的值不确定
组件状态 | this.props.children 获取结果 |
---|---|
没有子节点 | undefined |
一个子节点 | obj |
多个子节点 | array |
5.PropTypes
- 组件类的 PropTypes 属性,就是用来验证组件实例的属性是否符合要求
var data = 123;
class MyTitle extends React.Component {
propTypes :{
title: React.PropTypes.string.isRequired,
}
render() {
return <h1> {this.props.title} </h1>;
}
}
ReactDOM.render(
<MyTitle title={data} />,
document.getElementById('example')
);
6.模块生命周期
-
class extends React.Component
的生命周期函数:
- 可选的
static
方法 -
constructor
构造函数 -
getChildContext
获取子元素内容 -
componentWillMount
模块渲染前 -
componentDidMount
模块渲染后 -
componentWillReceiveProps
模块将接受新的数据 -
shouldComponentUpdate
判断模块需不需要重新渲染 -
componentWillUpdate
上面的方法返回true
, 模块将重新渲染 -
componentDidUpdate
模块渲染结束 -
componentWillUnmount
模块将从DOM中清除, 做一些清理任务 -
点击回调或者事件处理器 如
onClickSubmit()
或onChangeDescription()
-
render
里的 getter 方法 如getSelectReason()
或getFooterContent()
-
可选的 render 方法 如
renderNavigation()
或renderProfilePicture()
-
render
render() 方法
-
如何定义
propTypes
,defaultProps
,contextTypes
, 等等其他属性...import React from 'react'; import PropTypes from 'prop-types'; const propTypes = { id: PropTypes.number.isRequired, url: PropTypes.string.isRequired, text: PropTypes.string, }; const defaultProps = { text: 'Hello World', }; class Link extends React.Component { static methodsAreOk() { return true; } render() { return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>; } } Link.propTypes = propTypes; Link.defaultProps = defaultProps; export default Link;