簡體   English   中英

React.js:可重用組件與Mixin的實用程序功能

[英]React.js : reusable components vs mixin's utility functions

假設我的react.js應用程序將顯示日期,並且我想應用在客戶端的瀏覽器/操作系統中設置的格式。 有多個顯示日期的組件,我可以使用兩種方法在它們之間共享代碼。

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>
        );
    }
}); 

然后像這樣使用它們:

var DateFormatter = require('./../formatters/Date');
<DateFormatter value={invoice.date} />

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>
        );
    }
} 

然后只需將mixin添加到組件中並使用類似

{this.renderDate(invoice.date)}

在我看來,目前這兩種方法之間並沒有太大區別。 但是,我很想聽聽社區對於每種解決方案的利弊的意見。 TIA!

一個方面是性能:如果像上面那樣編寫組件以顯示日期,則可以使用PureRenderMixin對其進行標記 ,因為渲染的輸出僅取決於道具。 這可能會加快渲染速度,因為僅在日期更改時才需要進行格式化。

從干凈的代碼角度來看,我將編寫一個組件或使用一個僅將日期格式化為字符串的非反應實用程序函數-無需將日期格式化和dom元素結合在一起。 就像是:

function formatDate(dateValue){
    if(dateValue == null)
        return ""
    return new Date(dateValue).toLocaleDateString()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM