react学习(一)组件
react这个东西,说实话,我刚刚接触一个月不到。感觉这玩意很颠覆我以前的前端开发
比方说,可能,整个项目,并没有一个html文件
比方说,以前我们写前端代码,分的清清楚楚,html里面就是放dom,css里面放样式,js里面放逻辑处理
比方说...
手里头正好在写一个项目,也顺带着看着书,就稍微记一点自己的理解
组件
我觉得这个是react的核心了哇
以前也写组件,毕竟是加快开发的东西,就像雕版印刷最后发展到活字印刷的必然性。组件也是必然的。
可复用很重要,一个项目,甚至多个项目,肯定会有很类似的东西,他们往往只是某部分不同,差不多就这个意思,把不同的地方搞成个变量,恩,差不多就这样理解挺方便的
下面研究下react的组件
/**
* @file
* @author fengying
*/
import React, { PureComponent, PropTypes } from 'react';
import styles from './boxTitle.less';
export default class boxTitle extends PureComponent {
// 定义参数的类型以及是否为必须的,如果这边不是必须就要在defaultProps里面
static propTypes = {
title: PropTypes.string,
icon: PropTypes.bool.isRequired,
}
// 定义非必要的参数的默认值
static defaultProps = {
title: '',
}
// 构造函数,定义默认的state
constructor(props) {
super(props);
this.state = {
};
}
// 在render()方法执行前执行,只执行一次
componentWillMount() {
}
// 在render()方法执行后执行,只执行一次
componentDidMount() {
}
// 当组件传入的 props 发生变化时调用,例如:父组件状态改变,给子组件传入了新的prop值。用于组件 props 变化后,更新state。
componentWillReceiveProps(nextProps) {
// this.setState({ });
}
// 接受需要更新的props和state,让开发者增加必要的条件判断,让其在需要时更新,不需要时不更新,当方法返回false时,组件不再向下执行生命周期方法
shouldComponentUpdate(nextProps, nextState) {
}
// 重新渲染组件刷新前
componentWillUpdate() {
}
// 重新渲染组件刷新后
componentDidUpdate() {
}
// 组件销毁前(事件回收或者清除定时器等方法)
componentWillUnmount() {
}
render() {
const { title, icon } = this.props;
return (
<div className={styles.title}>
{
icon ? <span className={styles.tip} /> : ''
}
{title}
</div>
);
}
}
这个是项目里一个小标题
基本上可以作为一个模板,当然有些方法没用到的,可以删了
总结
生命周期三个状态:
- Mounting:已插入真实 DOM
- Updating:正在被重新渲染
- Unmounting:已移出真实 DOM
状态的处理函数:
- componentWillMount()
- componentDidMount()
- componentWillUpdate(object nextProps, object nextState)
- componentDidUpdate(object prevProps, object prevState)
- componentWillUnmount()
特殊的处理函数:
- componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用,DOM不会二次渲染
- shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用
render里面return的html,用{}包围起来写js代码
state改变,页面会重新渲染
setState方法是异步的,若要在改变state值后进行操作,记得写在回调函数里面

浙公网安备 33010602011771号