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 组件;
React 组件树,这棵树最终将会渲染成 HTML,
DOM 元素中;
DOM 节点;他们是 React
组件属性:
组件的属性可以在组件类的
让我们创建
props ),我们就可以读到从
示例:
var
Comment
=
React.createClass({
render:
function()
{
return
(
<div
className="comment">
<h2
className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
</div>
);
}
});
this.pros.children
注意:
React 提供一个工具方法
参考资料: http://www.ruanyifeng.com/blog/2015/03/react.html http://reactjs.cn/react/docs/tutorial.html
示例代码:
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.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
相关文章推荐
- ReactNative 第四节 实例开发
- React/React Native 的ES5 ES6写法对照表
- [转] 在React Native中使用ART
- react-native学习之环境安装
- Reactive Cocoa详解(1)----神奇的RAC宏
- React 组件的生命周期
- 在Mac上搭建React Native开发环境(iOS && Android)
- React入门教程(一)——JSX学习篇
- Windows搭建安装React Native环境配置
- Material-UI + React + Babel + Webpack 环境配置
- 从零开始学React(1)——HelloWorld
- 从零开始学React(2)——React语法
- 从零开始学React(3)——数组
- React学习笔记—组件复用
- React基础入门
- React-Native系列Android——通信数据模型分析
- React Native从入门到放弃
- ReactNative – 组件的生命周期
- React源码剖析系列 - 不可思议的react diff
- reactor和proactor模式