簡體   English   中英

在 React 中使用 HTML 中的 JS

[英]Using JS inside HTML with React

我有以下代碼:

<div className=''>
  <div className='userLayout'>
  {localMessages.map((localMessage) => (
    <div className={`${userId}` === `${localMessage.uuid}` ? 'fromUserLayout userCurrentLayout' : 'fromUserLayout userOtherLayout'} >
      <div className={`${userId}` === `${localMessage.uuid}` ? 'user userCurrent' : 'user userOther'}>
      <p>{localMessage.content}</p>
      <p>{localMessage.timestamp}</p>
      { localMessage?.image && localMessage.image.length > 0 && <img style={{width: '100%', height: 'auth', marginBottom: 24 }} src={localMessage.image} alt='chat' /> } 
   </div>
  </div>)
  )}
</div>

這有效,但是,我想將 localMessage.timestamp 中的時間戳轉換回日期。
我知道我可以用類似的東西來做到這一點:

let theDate = new Date(localMessage.timestamp)

但我不記得(或弄清楚)如何在 map function 中使用 JS。

我確實嘗試了{ let theDate = new Date(localMessage.timestamp) }但在開頭 {(意外關鍵字'let')和 theDate('}' 預期)上出現解析錯誤

你可以做:

<div className=''>
  <div className='userLayout'>
  {localMessages.map((localMessage) => (
    <div className={`${userId}` === `${localMessage.uuid}` ? 'fromUserLayout userCurrentLayout' : 'fromUserLayout userOtherLayout'} >
      <div className={`${userId}` === `${localMessage.uuid}` ? 'user userCurrent' : 'user userOther'}>
      <p>{localMessage.content}</p>

      <p>{new Date(localMessage.timestamp).toDateString()}</p>

      { localMessage?.image && localMessage.image.length > 0 && <img style={{width: '100%', height: 'auth', marginBottom: 24 }} src={localMessage.image} alt='chat' /> } 
   </div>
  </div>)
  )}
</div>

或者不使用toDateString() ,您可以使用toLocaleString()toLocaleDateString() ... 僅執行new Date(localMessage.timestamp)可能會返回 object,這可能會在 jsx 標記內重現錯誤。

暫無
暫無

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

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