简体   繁体   中英

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

I did try { let theDate = new Date(localMessage.timestamp) } but get parsing errors on the opening { (unexpected keyword 'let') and on theDate ( '}' expected)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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