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() 方法
参考
1.UI组件和container组件
UI组件是构成前端界面的基础单元,它们不涉及业务逻辑,无生命周期函数,只负责单纯的渲染,所有数据都通过 props 传入。
UI组件分为两种情况,有状态组件和无状态组件:
2. components导出默认模块
3.总是在Refs里使用回调函数
4.this.props.children
5.PropTypes
6.模块生命周期
class extends React.Component的生命周期函数:static方法constructor构造函数getChildContext获取子元素内容componentWillMount模块渲染前componentDidMount模块渲染后componentWillReceiveProps模块将接受新的数据shouldComponentUpdate判断模块需不需要重新渲染componentWillUpdate上面的方法返回true, 模块将重新渲染componentDidUpdate模块渲染结束componentWillUnmount模块将从DOM中清除, 做一些清理任务onClickSubmit()或onChangeDescription()render里的 getter 方法 如getSelectReason()或getFooterContent()renderNavigation()或renderProfilePicture()renderrender() 方法如何定义
propTypes,defaultProps,contextTypes, 等等其他属性...参考