加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React入门笔记(一)

发布时间:2020-12-15 03:33:54 所属栏目:百科 来源:网络整理
导读:环境配置 新版的React要求统一使用babel作为JSX的编译工具,因此我们选择babel,新建.babelrc文件,内容如下 { "presets":["es2015","react"] //设置候选版本为es6和react-jsx} 这里因为要用到ES6,所以把在babel候选版本里加入对ES6的支持 React组件 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
);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读