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

来源:互联网 发布:高考大数据志愿分析 编辑:程序博客网 时间:2024/05/29 03:18
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
原创粉丝点击