繁体   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