javascript - 在 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()
这里使用,但我不知道该怎么做。我不想重构使用一个类;它必须是一个功能组件。谢谢。
解决方案
我假设您想一次选择一张图像并显示它的标题。因此,这是一种幼稚的方法,您可以根据自己的情况进行调整。
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。
推荐阅读
- karate - 空手道 DSL:从响应中提取 XML 属性值
- html - Flex nowrap 容器不包裹孩子。当那些的宽度以百分比提到时
- github - 如果前一个失败但当前一个成功,有什么方法可以触发 Github 操作?
- flutter - 如何使用 Provider 实现注册/登录逻辑。颤振,飞镖,移动开发
- java - 当所有其他消息完成处理时,Spring集成处理消息
- json - 通过 Oauth 请求 Zoom API 的访问令牌 - 错误“缺少授权类型”
- node.js - MongoDb find().lean() 很慢
- linux - 'apt-get clean' 在带有 WSL2 的 Ubuntu 20.04 LST 中返回错误
- vue.js - 如何在没有直接访问的情况下模拟 vuex 函数?
- xamarin.forms - 使用 Prism NavigationService 实例化选项卡页面子视图模型的问题