您的位置:首页 > Web前端 > React

React入门教程(二)

2016-05-16 16:09 716 查看
React基础总结(续)

示例代码:

CommentBox
=
React.createClass({

displayName:
'CommentBox', 

render:
function()
{
 

return
(
 

React.createElement('div',
{className:
"commentBox"},
 

"Hello,
world! I am a CommentBox."  )
 

);
}

});

ReactDOM.render(

React.createElement(CommentBox,
null), 

document.getElementById('content')

);

解析:

React.createClass()
 来创建一个新的
React 组件;

 
render
 方法:该方法返回一棵
React 组件树,这棵树最终将会渲染成 HTML,
ReactDOM.render()
 实例化根组件,启动框架,把标记注入到第二个参数指定的原生的
DOM 元素中;

 
<div>
 标签:不是真正的
DOM 节点;他们是 React 
div
 组件的实例。

组件属性:

组件的属性可以在组件类的 
this.props
对象上获取,比如 
name
 属性就可以通过 
this.props.name
 读取。

让我们创建 
Comment
 组件,该组件依赖于从父级传入的数据。从父组件传入的数据会做为子组件的 
属性(
property )
 ,这些 
属性(
properties )
 可以通过 
this.props
 访问到。使用属性(
props ),我们就可以读到从 
CommentList
 传到 
Comment
 的数据,然后渲染一些标记:

示例:

var
Comment
=
React.createClass({ 

render:
function()
{
 

return
(
 

<div
className="comment">

<h2
className="commentAuthor">
{this.props.author}
</h2>
 

{this.props.children}
 

</div>
);

}

});



this.pros.children
this.props
 对象的属性与组件的属性一一对应,但是有一个例外,就是 
this.props.children
 属性。它表示组件的所有子节点
注意:

this.props.children
 的值有三种可能:如果当前组件没有子节点,它就是 
undefined
 ;如果有一个子节点,数据类型是 
object
 ;如果有多个子节点,数据类型就是 
array
 。所以,处理 
this.props.children
 的时候要小心。

React 提供一个工具方法 
React.Children
 来处理 
this.props.children
 。我们可以用 
React.Children.map
 来遍历子节点,而不用担心 
this.props.children
 的数据类型是 
undefined
 还是 
object
。更多的 
React.Children
 的方法
参考资料: http://www.ruanyifeng.com/blog/2015/03/react.html http://reactjs.cn/react/docs/tutorial.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: