英文:
React handle classNames on elements
问题
我有一个React应用程序,还有一个卡片列表。每张卡片都在一个div
中,并显示div
的一小部分内容。当单击div
时,它应该展开并显示所有内容。我可以通过向展开的div
添加一个额外的类名来实现这一点。那么在React中应该如何正确实现这个功能呢?
<div className="card" onClick={handleCardClick}>
卡片内容
</div>
关键是,我将拥有一系列的卡片,我不能仅使用useState()
来处理它们。我认为应该使用类似以下方式:
e.target.classList.add("expandCard")
但我不确定这是否是React中处理这些更改的正确方式。
英文:
I have react app and also have list of cards. Every card is in div and it shows small portion of content of the div. When you click on the div it should expand and show all content. That i can do it with adding more one className to the div that is expanded. So how it is proparly to this in react.
<div className="card" onClick={?}>
card conten
<div>
The point is i will have a lits of cards and i cant handle this with useState(). I thinks i should use somthing like:
e.target.classList.add("expandCard")
but i am not sure is that the right way to react handle the changes?
答案1
得分: 0
你需要在每张卡片中保持一个展开状态,并且如果展开了就显示内容。此外,你可以根据展开状态有条件地应用不同的类。
你可以从这段代码中获取一些想法:
import "./styles.css";
import { useState } from "react";
export default function App() {
const [cards, setCards] = useState([
{
id: 1,
title: "标题 1",
content: "内容 1"
},
{
id: 2,
title: "标题 2",
content: "内容 2"
},
{
id: 3,
title: "标题 3",
content: "内容 3"
}
]);
return (
<div>
{cards.map((card) => (
<Card key={card.id} title={card.title}>
{card.content}
</Card>
))}
</div>
);
}
function Card({ children, title }) {
const [expanded, setExpanded] = useState(false);
return (
<div className={`Card ${expanded ? "expandCard" : ""}`}>
<h1>{title}</h1>
<button onClick={() => setExpanded((prev) => !prev)}>显示内容</button>
{expanded && <p>{children}</p>}
</div>
);
}
英文:
You need to keep an expanded state in each card, and show the content if it is expanded. Also you can apply a different class conditionally if it is expanded.
You can get an idea from this code:
import "./styles.css";
import { useState } from "react";
export default function App() {
const [cards, setCards] = useState([
{
id: 1,
title: "title 1",
content: "content 1"
},
{
id: 2,
title: "title 2",
content: "content 2"
},
{
id: 3,
title: "title 3",
content: "content 3"
}
]);
return (
<div>
{cards.map((card) => (
<Card key={card.id} title={card.title}>
{card.content}
</Card>
))}
</div>
);
}
function Card({ children, title }) {
const [expanded, setExpanded] = useState(false);
return (
<div className={`Card ${expanded ? "expandCard" : ""}`}>
<h1>{title}</h1>
<button onClick={() => setExpanded((prev) => !prev)}>Show Content</button>
{expanded && <p>{children}</p>}
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论