簡體   English   中英

React 函數式組件有什么區別<message id>和js function formatMessage() 哪個更好用?</message>

[英]What is the difference between React functional component <Message id> and js function formatMessage() and which one is better to use?

我有以下代碼

消息組件:

import React from 'react';

const localizedMessages = {
   'title': 'This is my Title'
}

const Message = ({ id, ...params }) => {
  const msg = localizedMessages[id] || id;
  return <React.Fragment>{msg}</React.Fragment>;
};

export default Message;

還有一個util方法formatMessage(普通的javascript函數):

const localizedMessages = {
   'title': 'This is my Title'
}

export function formatMessage(id, params) {
  return localizedMessages[id] || id;
}

以及我想使用的實際組件

import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle } from '@material-ui/core';
import React from 'react';
import Message from './Message';
import formatMessage from './utils';

const MyComponent = () => {

  return <Dialog
    open={true}
    keepMounted
    maxWidth="sm"
  >
    <DialogTitle id="alert-dialog-slide-title">
      <Message id="title" />
      {formatMessage('title')}
    </DialogTitle>
    <DialogContent>
      <DialogContentText id="alert-dialog-slide-description">
        {content}
      </DialogContentText>
    </DialogContent>
    <DialogActions>
      <Button onClick={onClose} color="primary">
        <Message id="cancel" />
        {formatMessage('cancel')}
      </Button>
      <PrimaryButton onClick={onConfirmClick}>
        <Message id="yes" />
        {formatMessage('yes')}
      </PrimaryButton>
    </DialogActions>
  </Dialog>;
};

export default MyComponent;

我可以使用 < Message /> 或 formatMessage,兩者都會為我完成工作。 我更傾向於<Message />。

注意:從 < Message /> 和 formatMessage() 中刪除了與參數相關的代碼,以避免偏離實際問題。 參數用於插值。

您的組件不包含函數的任何附加功能:它們都只是通過其鍵返回純文本值。

在這種情況下,我認為沒有任何理由使代碼復雜化並使用組件。

使用組件不僅表明您正在進行某種圖形渲染或數據獲取(在這種情況下不是),而且還會使您的代碼更加冗長和冗長,這通常是我們嘗試的事情避免。
在您的示例中,您只使用一個參數,但是當您有更多 arguments 時,這會更加明顯:

<Message
  arg1={1}
  arg2={2}
  arg3={3}
/>

或者

formatMessage(1, 2, 3)

暫無
暫無

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

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