简体   繁体   English

在 React 中使用 HTML 中的 JS

[英]Using JS inside HTML with React

I have the following code:我有以下代码:

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

which works, however, I want to convert my timestamp in localMessage.timestamp back to a date.这有效,但是,我想将 localMessage.timestamp 中的时间戳转换回日期。
I know I could do this with something like:我知道我可以用类似的东西来做到这一点:

let theDate = new Date(localMessage.timestamp)

but I can't remember (or figure out) how to use JS inside the map function.但我不记得(或弄清楚)如何在 map function 中使用 JS。

I did try { let theDate = new Date(localMessage.timestamp) } but get parsing errors on the opening { (unexpected keyword 'let') and on theDate ( '}' expected)我确实尝试了{ let theDate = new Date(localMessage.timestamp) }但在开头 {(意外关键字'let')和 theDate('}' 预期)上出现解析错误

You can do:你可以做:

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

Or instead of using toDateString() you can use toLocaleString() , toLocaleDateString() ... Doing just new Date(localMessage.timestamp) could return an object, which could reproduce an error inside a jsx tag.或者不使用toDateString() ,您可以使用toLocaleString()toLocaleDateString() ... 仅执行new Date(localMessage.timestamp)可能会返回 object,这可能会在 jsx 标记内重现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM