前言
实习第二周,被告知要用React与导师进行基于React的Javaweb 的开发,jinzhangaaaaa~由于React 这款框架没学过,看了一峰老师的基础入门教程,硬着头皮开始上了...
组件的复用
实现基本的需求之后,校阅代码时,发现 A 组件内有大量相似的代码,代码不够简洁,自然而然想到组件的复用。
先上demo:
Titlevar HelloReact = React.createClass({
// propTypes :{
// title: React.PropTypes.string.isRequired,
// },
// getDefaultProps : function () {
// return {
// name : " hello React"
// };
// },
// 渲染的 HTML 内容
render : function () {
return
{this.props.title}
{this.props.name}
}
});
// 子组件 : 全局定义 或者是在 父组件内定义均可
// 父组件里有很多数据[比如head,content] 需要从 父组件(调用)传递给子组件(定义),
// 在这里加上组件模板
var Child = React.createClass({
render: function() {
return
标题: {this.props.head}
内容 :{this.props.content}
}
});
// var data = "123";
// var name = "React";
ReactDOM.render(
,
document.getElementById('app')
);
以上的demo 的代码注释已经尽量详细,这里有个至今较为困惑的点:父子组件的关系明确;我的简单理解是;同一个的Child 组件 ,定义时,它为子组件,而在使用调用时,则为父组件; 若有错误,欢迎大家的指正!
写完demo,结合项目,开始改改改...
该项目属于老项目,现在的工作是在原来的基础上新增部分类似的功能板块,同时做相关的优化
项目组件文件夹的结构目录
app
components
ConsumeBill.jsx -----A 组件=demo中的HelloReact
ChildBill.jsx ------Child 组件
....
...
...
在A组件中需要引入Child 组件,在其 render方法中多次使用 Child组件 。[考虑代码阅读:将Child组件以外部文件的方式引入;若Child组件的HTML 代码非常简短,可无需外部引入,同demo中类似直接放在A组件的React.createClass语句中] ;
继续先上demo:
Titlevar HelloReact = React.createClass({
// propTypes :{
// title: React.PropTypes.string.isRequired,
// },
// getDefaultProps : function () {
// return {
// name : " hello React"
// };
// },
// 渲染的 HTML 内容,
// 这里注意: JS语句 写在HelloReact组件中return [return 是React语句]外面,在HelloReact 组件的 **render方法**里面
render : function () {
let datas1 = {head:"我是标题1",content:"我是内容1"};
let datas2 = {head:"我是标题2",content:"我是内容2"};
return
{this.props.title}
{this.props.name}
}
});
// 子组件 : 全局定义 或者是在 父组件内定义均可
// 父组件里有很多数据[比如head,content] 需要从 父组件(调用)传递给子组件(定义),
// 在这里加上组件模板
var Child = React.createClass({
render: function() {
// ES6 语法对象解购赋值,可在Raect 语句中直接使用 head ,cotent
let {head="", content=""} = this.props.datas;
return
标题: {head}
内容 :{content}
}
});
// var data = "123";
// var name = "React";
ReactDOM.render(
,
document.getElementById('app')
);
*注意: JS语句 写在Father组件中return [return 里是React语句]外面,在Father 组件的render方法*里面
上面例子的demo:HelloReact 与 Child 组件是在同一文件(组件)内;外部引入呢?只要的Child部分代码 以外部文件引入则可,后续补充。