如何在点击地图功能上设置单个项目的边框颜色



我有一个由一些数据组成的数组。我的阵列是

const faqData = [
{
q: "How Can We Help You?",
a: "Below are answers to our most commonly asked questions. If you cannot find an answer here, please contact us.",
},
{
q: "How Can We Help You?",
a: "Below are answers to our most commonly asked questions. If you cannot find an answer here, please contact us.",
},
{
q: "How Can We Help You?",
a: "Below are answers to our most commonly asked questions. If you cannot find an answer here, please contact us.",
},
];

为了显示卡内阵列的所有数据,我正在使用地图功能,即

{faqData.map((item, index) => {
return (
<SimpleFlexContainer
sx={{ flexDirection: "column", m: "20px 0px" }}
>
<SimpleFlexContainer
sx={{
background: "#F4F4F5",
width: "100%",
p: "15px 25px",
justifyContent: "space-between",
alignItems: "center",
}}
>
<SimpleFlexContainer>
<SmallTypo
sx={{ fontWeight: "bold", mr: { xs: "15px", md: "25px" } }}
>
Question
</SmallTypo>
<SmallTypo sx={{ fontWeight: "bold" }}>{item.q}</SmallTypo>
</SimpleFlexContainer>
<Box>
<IconButton>
{openDes ? (
<RemoveIcon onClick={() => setDes(false)} />
) : (
<AddIcon onClick={() => setDes(true)} />
)}
</IconButton>
</Box>
</SimpleFlexContainer>
<Box
sx={{
display: openDes ? "inherit" : "none",
background: "white",
p: "26px",
border: "1px solid #F4F4F5",
}}
>
<SmallTypo>{item.a}</SmallTypo>
</Box>
</SimpleFlexContainer>
);
})}

当用户点击单个卡片时,我想在特定卡片周围显示一个边框颜色。如何做到这一点?

使用state保持单击项目的索引

const [clicked, setClicked] = React.useState('')

然后,你可以在一个像一样的外部SimpleFlexContainer中有一个样式

sx={{borderColor: clicked === index ? 'your_favourite_color': ''}}

当在外部单击时,不要忘记删除索引值,如果不介意的话,也可以保留它。

最好的解决方案是创建一个单独的组件。类似这样的东西:

import { useState } from 'React';
const FAQComponent = (props) => {
const {
item,
} = props;

const [active, setActive] = useState(false);
const [openDes, setDes] = useState(false);
return (
<SimpleFlexContainer
sx={{ flexDirection: "column", m: "20px 0px" }}
onClick={() => setActive(pre => !pre)}
>
<SimpleFlexContainer
sx={{
background: "#F4F4F5",
width: "100%",
p: "15px 25px",
justifyContent: "space-between",
alignItems: "center",
}}
>
<SimpleFlexContainer>
<SmallTypo
sx={{ fontWeight: "bold", mr: { xs: "15px", md: "25px" } }}
>
Question
</SmallTypo>
<SmallTypo sx={{ fontWeight: "bold" }}>{item.q}</SmallTypo>
</SimpleFlexContainer>
<Box>
<IconButton>
{openDes ? (
<RemoveIcon onClick={() => setDes(false)} />
) : (
<AddIcon onClick={() => setDes(true)} />
)}
</IconButton>
</Box>
</SimpleFlexContainer>
<Box
sx={{
display: openDes ? "inherit" : "none",
background: "white",
p: "26px",
border: "1px solid #F4F4F5",
}}
>
<SmallTypo>{item.a}</SmallTypo>
</Box>
</SimpleFlexContainer>
)
}

现在你可以把你的组件映射到其他地方:

{faqData.map((item, index) => <FAQComponent key={item.a} item={item} />)}

注意:React将key参数放在映射组件上非常重要,您可以使用项对象中唯一的任何其他字段。

然后,使用active常量来确定是否应该更改边界。

最新更新