前边的ReactJS基础,咱们能够了解到,对于React,能够说是万物皆组件框架 React的组件应该具备 可组合(Composeable)可重用(Reusable)可维护(Maintainable)的特征,因此咱们尽可能将组件最小化,写的尽量的小函数 前边已经介绍了组件的写法,下面咱们来进一步了解一下组件的属性、状态、生命周期和嵌套this |
咱们来编写一个组件SayHello,有一个name属性,而后输出hello + name的值,代码以下:spa
var SayHello = React.createClass({ render:function(){ return <h1 style={{color:"red"}}>hello {this.props.name}</h1> } }); ReactDOM.render( <SayHello name="lyx" />, document.getElementById('great') )
结果3d
有些细节须要注意:code
1.建立的组件名称首字母必须大写。
2.<SayHello name="lyx" />与 document.getElementById('great')之间用的是逗号分隔
3.获取属性的值用的是 this.props.属性名component
4.组件的style属性的设置方式也值得注意,要写成style={{width:“”100"}}这种形式orm
组件免不了要与用户互动,React 的一大创新,就是将组件当作是一个状态机,一开始有一个初始状态,而后用户互动,致使状态变化,从而触发从新渲染 UI 。咱们来看代码对象
var Counter = React.createClass({ getInitialState: function () { return { clickCount: 0 }; }, handleClick: function () { this.setState(function(state) { return {clickCount: state.clickCount + 1}; }); }, render: function () { return (<h2 onClick={this.handleClick}>点我!点击次数为: {this.state.clickCount}</h2>); } });
上面代码实现的是点击h2,显示点击次数,效果如图所示blog
须要注意是的是
1.getInitialState函数必须有返回值,能够是NULL或者一个对象。
2.访问state的方法是this.state.属性名。
3.变量用 { }包裹,不须要再加双引号。
前边咱们说了,组件要有复用的特色,线面来看一下如何复用
来看下边的代码
var Form= React.createClass({ render:function(){ return <div> {this.props.inputName}:<input type="text"/> </div> } }); var Iname= React.createClass({ render : function(){ return <div> <h3>欢迎</h3> <Form inputName="姓名"/> <Form inputName="电话"/> <button>submit</button> </div> } }); ReactDOM.render( <Iname />, document.getElementById('sub') )
这里咱们建立了一个Form组件,而后又建立了一个Iname组件,而后咱们在Inmae组件中调用Form组件两次,这里咱们经过属性inputName传入值
组件的生命周期可分红三个状态:
生命周期的方法有:
componentWillMount 在渲染前调用,在客户端也在服务端。
componentDidMount : 在第一次渲染后调用,只在客户端。以后组件已经生成了对应的DOM结构,能够经过this.getDOMNode()来进行访问。 若是你想和其余JavaScript框架一块儿使用,能够在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操做(防止异部操做阻塞UI)。
componentWillReceiveProps 在组件接收到一个新的prop时被调用。这个方法在初始化render时不会被调用。
shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
能够在你确认不须要更新组件时使用。
componentWillUpdate在组件接收到新的props或者state但尚未render时被调用。在初始化时不会被调用。
componentDidUpdate 在组件完成更新后当即调用。在初始化时不会被调用。
componentWillUnmount在组件从 DOM 中移除的时候马上被调用。
这些就跟PHP中的一些魔术方法同样,知足条件自动调用,
下面以componentDidMount方法为例,
var Hello = React.createClass({ getInitialState: function () { return { color: "red" }; }, componentDidMount: function () { alert("111"); }, render: function () { return ( <div style={{color: this.state.color}}> Hello {this.props.name} </div> ); } });
此方法是第一次渲染后调用,就有以下结果