首页 > 解决方案 > 在 React 中选择图像并显示标题

问题描述

我有一个 React 功能组件,其中包含带有标题的图像列表:

export function MyComponent() {
  const images = [
    { image: "http://www.example1.com/image1.jpg", title: "Title 1"},
    { image: "http://www.example2.com/image2.jpg", title: "Title 2"},
    { image: "http://www.example3.com/image3.jpg", title: "Title 3"}
  ]

  const [titles, setTitles] = React.useState([]);

  return (
    <div>

      <div>{titles}</div>

      <section className="images">{
        images.map(image => (
          <img
            src={image.image}
            alt={image.title}
            onClick={() => {}} // selects or unselects the image?
          />
          )
        )}</section>
    </div>
  );
}

当我单击图像时,我希望它被选中或取消选中。当它被选中时,我想要一个 CSS 边框出现。如果选择了图像,我希望所选图像标题列表出现在<div>{titles}</div>. 我想在React.useState()这里使用,但我不知道该怎么做。我不想重构使用一个类;它必须是一个功能组件。谢谢。

标签: javascriptreactjstypescript

解决方案


我假设您想一次选择一张图像并显示它的标题。因此,这是一种幼稚的方法,您可以根据自己的情况进行调整。

const images = [
  { image: "https://via.placeholder.com/150", title: "Title 1" },
  { image: "https://via.placeholder.com/150", title: "Title 2" },
  { image: "https://via.placeholder.com/150", title: "Title 3" },
];

function Main() {
  const [selected, setSelected] = React.useState();

  return (
    <div>
      <div>{images[selected] && images[selected].title}</div>

      <section className="images">
        {images.map((image, index) => (
          <img
            className={index === selected ? "selected" : ""}
            key={`${index}${image.title}`}
            src={image.image}
            alt={image.title}
            onClick={() => setSelected(index)}
          />
        ))}
      </section>
    </div>
  );
}

ReactDOM.render(<Main />, document.getElementById("root"));
.selected {
  border: 5px solid black;
}
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root" />

所以,你有一个状态, selected index。对于className您查找图像的部分index,与状态进行比较,selected然后根据该状态分配一个类名。对于标题部分,您只是通过使用带有条件 JSXtitle的 selected 来获取。index

但是,使用索引并不可靠。最好为图像设置一些唯一的 id。


推荐阅读