React入门笔记(一)
环境配置新版的React要求统一使用babel作为JSX的编译工具,因此我们选择babel,新建.babelrc文件,内容如下 { "presets":["es2015","react"] //设置候选版本为es6和react-jsx } 这里因为要用到ES6,所以把在babel候选版本里加入对ES6的支持 React组件React里引入的组件这个概念: 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 React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。 componentWillMount() 下图是官方文档里对各种函数执行位置的表述
这里我们做个实验: 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 ); 运行程序,控制台输出结果如下:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |