React入门笔记(一)

发布时间:2019-06-23 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React入门笔记(一)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

环境配置

新版的React要求统一使用babel作为JSX的编译工具,因此我们选择babel,新建.babelrc文件,内容如下

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

这里因为要用到ES6,所以把在babel候选版本里加入对ES6的支持

React组件

React里引入的组件这个概念:
React里的组件就像Android,ios里的控件一样,能方便快捷的作为界面的一部分实现一定功能,我们可以把数据传入:

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

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

同样的组件我们用ES6实现如下:

class Hello extends React.Component {

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

}

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

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

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

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

组件的生命周期

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

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

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

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

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

React入门笔记(一)

这里我们做个实验:

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
);

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

React入门笔记(一)

脚本宝典总结

以上是脚本宝典为你收集整理的React入门笔记(一)全部内容,希望文章能够帮你解决React入门笔记(一)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:es6