react 学习--组件的生命周期(一)初始化阶段

var style = {
        "width":"100%",
        "lineheight":"30px",
        "color":"red",
        "border":"solid 1px gray"
    };

    var count = 0;

    // 定义一个helloworld组件
    var HelloWorld = React.createClass({
        // 1.只调用一次,实例之间共享引用
        getDefaultProps:function () {
            console.log("getDefaultProps,1");
            return {
                name:"Tom"
            };
        },
        // 2.初始化每个实例特有的状态
        getInitialState:function () {
            console.log("getInitialState,2");
            return {
                myCount:count++,
                ready:false
            };
        },
        // 3.render之前最后一次修改状态
        componentWillMount:function () {
            console.log("componentWillMount,3");
            this.setState({
                ready:true
            })
        },
        // 4.只能访问this.props和this.state,不允许修改状态和dom输出
        render:function () {
            console.log("render,4");
            return (
                    <div style={style}>
                        <p ref="childp">{this.state.myCount},Hello,{(function (obj) {
                            return obj.props.name||"world";
                        })(this)}<br/>{this.state.ready}</p>
                    </div>
            );
        },
        // 5.只调用一次,等页面上所有组件渲染真实的DOM完毕后,可修改DOM
        componentDidMount:function () {
            console.log("componentDidMount,5");
            ReactDOM.findDOMNode(this).innerHTML += " haha";
        }

    });
    // 渲染节点
    ReactDOM.render(<div><HelloWorld name = "xiaopeng"/><br/>
                    <HelloWorld name = "xiaopeng"/><br/>
                    <HelloWorld name = "xiaopeng"/><br/>
                    </div>,document.getElementById("app"));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值