react学习(一)组件

react这个东西,说实话,我刚刚接触一个月不到。感受这玩意很颠覆我之前的前端开发javascript

比方说,可能,整个项目,并无一个html文件css

比方说,之前咱们写前端代码,分的清清楚楚,html里面就是放dom,css里面放样式,js里面放逻辑处理html

比方说...前端

手里头正好在写一个项目,也顺带着看着书,就稍微记一点本身的理解java

组件

我以为这个是react的核心了哇react

之前也写组件,毕竟是加快开发的东西,就像雕版印刷最后发展到活字印刷的必然性。组件也是必然的。less

可复用很重要,一个项目,甚至多个项目,确定会有很相似的东西,他们每每只是某部分不一样,差很少就这个意思,把不一样的地方搞成个变量,恩,差很少就这样理解挺方便的dom

下面研究下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值后进行操做,记得写在回调函数里面

相关文章
相关标签/搜索