微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

这里我们做个实验:

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 ',document.body
);

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

原文地址:https://www.jb51.cc/react/306825.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐