我可以在图像标签中使用三元运算符吗?

Can I use a ternary operator inside of an image tag?

我正在尝试在图像标签内使用三元运算符在两组 gif 之间切换。它不工作。我的语法搞砸了吗,还是我不能这样做?有什么建议么? (下面的代码)

import React, { useState } from 'react'

const Artist = ({currentArtist}) => {
    const ghostify = () => {
       if(isGhost) {
            setIsGhost(!isGhost)
        } 
    }

    //state
    const [isGhost, setIsGhost] = useState(false)

    return (
        <div className="artist">
            <img src={isGhost ? currentArtist.vid : currentArtist.ghostVid} alt= 
                {currentArtist.name} />
            <h2>{currentArtist.name}</h2>
            <h3>{currentArtist.title}</h3>
            <button onClick={ghostify()}>Ghostify</button>
        </div>
    )
}

export default Artist

根据我所看到的进行,因为您的问题没有错误,而且根据记忆 onClick:

<button onClick={ghostify()}>Ghostify</button>

将始终触发(从“”学习)所以它应该是:

<button onClick={() => ghostify}>Ghostify</button>

一些建议。我总是喜欢声明我的 useStateuseEffect 我想说我 read it was advised.

我认为您不需要检查函数的条件,所以:

const ghostify = () => {
    if(isGhost) {
        setIsGhost(!isGhost)
    } 
}

将是:

const ghostify = () => setIsGhost(!isGhost)

我更喜欢解构,当你并不总是知道你是否会有 nametitle 时,我喜欢设置默认值或条件渲染。我会将您的组件更改为 nametitle:

的条件
import React, { useState } from 'react'

const Artist = ({ currentArtist }) => {
  const [isGhost, setIsGhost] = useState(false)
  const ghostify = () => setIsGhost(!isGhost)
  const { vid, ghostVid, name, title } = currentArtist

  return (
    <div className='artist'>
      <img src={isGhost ? vid : ghostVid} alt={name} />
      {name && <h2>{name}</h2>}
      {title && <h3>{title}</h3>}
      <button onClick={() => ghostify}>Ghostify</button>
    </div>
  )
}

export default Artist