React入门笔记(一)

环境配置

新版的React要求统一使用babel做为JSX的编译工具,所以咱们选择babel,新建.babelrc文件,内容以下react

{
    "presets":["es2015","react"]       //设置候选版本为es6和react-jsx
}

这里由于要用到ES6,因此把在babel候选版本里加入对ES6的支持ios

React组件

React里引入的组件这个概念:
React里的组件就像Android,ios里的控件同样,能方便快捷的做为界面的一部分实现必定功能,咱们能够把数据传入:es6

var Hello = React.createClass({
    render: function () {
        return (
            <div>
                <h1>
                    {this.props.name}
                </h1>
            </div>
        );
    }
});

这里咱们用React.createClass方法建立了一个React组件,render函数的返回值为要渲染的内容。babel

一样的组件咱们用ES6实现以下:函数

class Hello extends React.Component {

    render() {
        return (
            <div>
                <h1>
                    {this.props.name}
                </h1>
            </div>
        );
    }

}

这里用到了ES6的class、extends等关键词工具

接下来咱们用ReactDOM.render方法将其render到页面上this

let names = [
    'flypie ',
    'flyboy '
];

ReactDOM.render(
    <Hello name={names}/>,
    document.body
);

组件的生命周期

组件的生命周期分红三个状态:spa

Mounting:已插入真实 DOM
Updating:正在被从新渲染
Unmounting:已移出真实 DOMcode

React 为每一个状态都提供了两种处理函数,will 函数在进入状态以前调用,did 函数在进入状态以后调用,三种状态共计五种处理函数。component

componentWillMount()
componentDidMount()
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
componentWillUnmount()

下图是官方文档里对各类函数执行位置的表述

图片描述

这里咱们作个实验:

let Hello = React.createClass({

    getInitialState: function () {
        console.log('getInitialState');
        return {};
    },

    getDefaultProps: function () {
        console.log('getDefaultProps');
        return {};
    },

    componentWillMount: function () {
        console.log('componentWillMount');
    },

    componentDidMount: function () {
        console.log('componentDidMount');
    },

    componentWillReceiveProps: function () {
        console.log('componentWillReceiveProps');
    },

    shouldComponentUpdate: function () {
        console.log('shouldComponentUpdate');
        return true;
    },

    componentWillUpdate:function(){
        console.log('componentWillUpdate');
    },

    componentDidUpdate:function(){
        console.log('componentDidUpdate');
    },

    componentWillUnmount:function(){
        console.log('componentWillUnmount');
    },

    render: function () {
        return (
            <div>
                <h1>
                    {this.props.name}
                </h1>
            </div>
        );
    }
});

let names = [
    'flypie ',
    'flyboy '
];

ReactDOM.render(
    <Hello name={names}/>,
    document.body
);

运行程序,控制台输出结果以下:

图片描述

相关文章
相关标签/搜索