[英]React.js : reusable components vs mixin's utility functions
Let's say my react.js app is going to display dates and I would like to apply the format that is set in the client's browser/OS. 假设我的react.js应用程序将显示日期,并且我想应用在客户端的浏览器/操作系统中设置的格式。 There are multiple components that show dates and I can use a couple of ways to share the code between them.
有多个显示日期的组件,我可以使用两种方法在它们之间共享代码。
1.Re-usable React.js components like: 1.可重用的React.js组件,例如:
var React = require('react');
module.exports = React.createClass({
render : function(){
if(this.props.value === null || this.props.value===undefined)
return false;
var formattedValue = new Date(this.props.value).toLocaleDateString();
return(
<span>
{formattedValue}
</span>
);
}
});
and then use them like: 然后像这样使用它们:
var DateFormatter = require('./../formatters/Date');
<DateFormatter value={invoice.date} />
2.Utility functions shared via React.js mixins, ie: 2.通过React.js mixins共享的实用功能,即:
module.exports = {
renderDate : function(dateValue){
if(dateValue === null || dateValue===undefined)
return false;
var formattedValue = new Date(dateValue).toLocaleDateString();
return(
<span>
{formattedValue}
</span>
);
}
}
and then just add the mixin to a component and use something like 然后只需将mixin添加到组件中并使用类似
{this.renderDate(invoice.date)}
To me it seems that there is no much difference between these 2 approaches for now. 在我看来,目前这两种方法之间并没有太大区别。 But I would love to hear the opinion of community about pros and cons of each solution.
但是,我很想听听社区对于每种解决方案的利弊的意见。 TIA!
TIA!
One aspect is performance: if you write a component to display the date like you did above, you can mark it with PureRenderMixin , as the rendered output relies only on the the props. 一个方面是性能:如果像上面那样编写组件以显示日期,则可以使用PureRenderMixin对其进行标记 ,因为渲染的输出仅取决于道具。 This might speed up the rendering a bit, as the formatting only needs to be done when the date changes.
这可能会加快渲染速度,因为仅在日期更改时才需要进行格式化。
From clean code point of view, I would either write a component or use a non-react utility function that just formats the date to a string - no need to couple the date formatting and dom elements. 从干净的代码角度来看,我将编写一个组件或使用一个仅将日期格式化为字符串的非反应实用程序函数-无需将日期格式化和dom元素结合在一起。 Something like:
就像是:
function formatDate(dateValue){
if(dateValue == null)
return ""
return new Date(dateValue).toLocaleDateString()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.