React useState:如何将三元运算符放在三元运算符中?

React useState: How to put ternary operator within a ternary operator?

我正在映射一组项目。有些项目必须显示视频,而其他项目则必须显示图像。我为每个显示器制作了 2 个函数,我正在使用 useState 来切换它们。

export default function App() {
  //SIMPLE USESTATE TO TOGGLE WINDOW
  const [open, setOpen] = useState(false);

  //THE ARRAY (1 contains an image and the other a video)
  const itemsArray = [
    {
      name: "Item1",
      imageUrl: "some image url"
    },
    {
      name: "Item2",
      videoUrl: "some video url"
    }
  ];

  //RENDER THIS IF ITEM IS IMAGE
  const ifImage = (i) => {
    return (
      <div onClick={() => setOpen(!open)}>
        <img src={i} alt="cat" />
      </div>
    );
  };

  //RENDER THIS IF ITEM IS VIDEO
  const ifVideo = (v) => {
    return (
      <div className="window-on-top" onClick={() => setOpen(!open)}>
        <iframe>Some Video</iframe>
      </div>
    );
  };

  return (
    <div className="App">
      <h3>One button shows a cat photo and the other a cat video</h3>
      {itemsArray.map((item) => {
        return (
          <div key={item.name}>
            <button className="niceBtn" onClick={() => setOpen(!open)}>
              {item.name}
            </button>

            {/* NESTING CONDITIONALS OR SOMETHING TO MAKE THIS WORK */}
            {open ? {
          {item.imageUrl ? ifImage(item.imageUrl): null}
          ||
          {item.videoUrl ? ifVideo(item.videoUrl): null}
        } : null}
          </div>
        );
      })}
    </div>
  );
}

我显然错了...需要一些帮助以了解如何解决此问题... 这是一个带有正确观看代码的沙盒。 SANDBOX

我会把条件放在子函数中,这样应该更容易理解正在发生的事情。

const tryImage = item => (
    !item.imageUrl ? null : (
        <div onClick={() => setOpen(!open)}>
            <img src={item.imageUrl} alt="cat" />
        </div>
    ));
const tryVideo = item => (
    !item.videoUrl ? null : (
        <div onClick={() => setOpen(!open)}>
            <img src={item.videoUrl} alt="cat" />
        </div>
    ));

return (
    <div className="App">
        <h3>One button shows a cat photo and the other a cat video</h3>
        {itemsArray.map((item) => {
            return (
                <div key={item.name}>
                    <button className="niceBtn" onClick={() => setOpen(!open)}>
                        {item.name}
                    </button>
                    {open && ([
                        tryImage(item),
                        tryVideo(item),
                    ])}
                </div>
            );
        })}
    </div>
);

不确定,但您可能还希望数组中的每个项目都有一个单独的 open 状态,而不是整个应用的单一状态。