React.js终探(七)(完)

我们在前面介绍了组件的各种特性,这一节我们来说说多组件的情况。

在实际开发中,我们的组件难免会遇到有公共部分的情况,如果是个别情况还好,但如果数量比较多的话,那这时候,就需要公用了。

怎么公用呢?

React为我们提供了它的方法。

mixin:复用代码

可以把部分代码提出来公用。mixin是掺合混合的意思,即可以把一个对象的属性拷贝到另一个对象上。

使用mixin有两步:

  • 定义一个mixin对象,即如
 var EzLoggerMixin = {
log:function(){
//sth. happened here.
}
};
  • 使用React.createClass时,给传入的原型对象设置mixins属性
 React.createClass({
mixins:[EzLoggerMixin],
render:function(){
//your render stuff.
}
});

可以看出,mixins属性是一个数组,表示可以传多个mixin对象,但是注意注意,传入的mixin对象中,不要有同名属性

来个例子:

React.js终探(七)(完)

定义一个日志的mixin对象,React组件使用mixin获得日志的输入能力。

上代码:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Component Mixins</title>
<script src="lib/react.js"></script>
<script src="lib/JSXTransformer.js"></script>
<style>
.ez-logger{
position:fixed;
left:0px;
bottom:0px;
height:100px;
width:100%;
background:#000;
color:#fff;
}
</style>
</head>
<body>
<div id="content"></div>
<script type = "text/jsx">
//日志mixin
var EzLoggerMixin = {
log:function(txt){
//按需撞见日志板DOM对象
if(!window._logger_){
var el = window._logger_ = document.createElement("pre");
el.className = "ez-logger";
document.body.appendChild(el);
}
//计算时间戳
var time = new Date,
h = time.getHours(),
m = time.getMinutes(),
s = time.getSeconds(),
ts = [h,m,s].join(":"); //this.constructor.displayName表示组件的显示名,React自动设置该属性
var compName = "[" + this.constructor.displayName + "]"; //输出到日志板
window._logger_.innerText = [window._logger_.innerText, ts + compName + " : " + txt].join("\n");
}
};
//组件1定义
var EzDemo1Comp = React.createClass({
mixins : [EzLoggerMixin], //使用日志mixin
componentDidMount : function(){
this.log("component rendered!");
},
render : function(){
this.log("rendering the component");
return <div>
<p>This is a demo component.</p>
</div>;
}
});
//组件2定义
var EzDemo2Comp = React.createClass({
mixins : [EzLoggerMixin], //使用日志mixin
componentDidMount : function(){
this.log("component rendered!");
},
render : function(){
this.log("rendering the component");
return <div>
<p>This is another demo component.</p>
</div>;
}
});
//渲染
React.render(
<div>
<EzDemo1Comp/>
<EzDemo2Comp/>
</div>,
document.querySelector("#content"));
</script>
</body>
</html>

值得一提的是:

this.constructor.displayName是获得当前组件的显示名,这个是React自动设置的属性

好了,探索React的学习的系列大体就到这里了。之后必要的话,会继续深入写React相关的。谢谢大家思密达

上一篇:深入剖析ThreadLocal


下一篇:C# WebService 概念,创建及引用调用