抓取url片段并展开相关的手风琴,滚动到它



我想发送带有链接到我的faq网站的邮件,比如http://www.test.com/faq#lorem_ipsum.

但我的faq网站是用多个手风琴组件制作的。

const faqQuestions = [
{
title: <h1 className="font-bold">question?</h1>,
content: (
<div className="px-4">
test
</div>
),
accordionId: 'lorem_ipsum',
},
]
const Faq = () => {
// const [isExpanded, setIsExpanded] = useState(false);
useLayoutEffect(() => {
const anchor = window.location.hash.split('#')[1];
if (anchor) {
const anchorEl = document.getElementById(anchor);
if (anchorEl) {
anchorEl.scrollIntoView();
}
}
}, []);
return (
<div className="container mx-auto px-10 lg:px-0">
<div className="py-6">
<p className="font-semibold text-3xl  text-primary">Häufige Fragen</p>
</div>
<div className="pb-10">
{faqQuestions.map((question) => (
<Accordion key={Math.random()} id={question.accordionId}>
<AccordionSummary
expandIcon={<FontAwesomeIcon icon={faChevronDown} />}
aria-controls="panel1a-content"
>
<div>{question.title}</div>
</AccordionSummary>
<AccordionDetails>{question.content}</AccordionDetails>
</Accordion>
))}
</div>
</div>
);
};

我希望,当用户点击带有锚点的链接,跳到特定的手风琴并展开它时。但我不知道如何识别我跳到的手风琴。使用简单的javascript很容易,但我找不到React的解决方案。

希望有人能帮助我。

如mui文档中所述,您需要使用受控手风琴,使用状态。

首先,添加一个状态以保留打开手风琴的名称/id。

const [expanded, setExpanded] = useState(false);

然后,更改更新函数,以便从URL中获取哈希,检查数组中是否存在匹配的问题,将相关的手风琴组件设置为展开,最后滚动到它。

useLayoutEffect(() => {
const anchor = window.location.hash.split('#')[1];
if (anchor) {
const accExists = faqQuestions.find(q => q.accordionId === anchor)
if (accExists) {
setExpandend(anchor);
const anchorEl = document.getElementById(anchor);
anchorEl.scrollIntoView();
}
}
}, []);

您还需要为受控手风琴上的点击添加一个处理程序,以使用点击手风琴的名称更新状态。

const handleChange = (panel) => (event, isExpanded) => {
setExpanded(isExpanded ? panel : false);
};

最后,更改JSX代码以使用此逻辑。

{faqQuestions.map((question) => (
<Accordion
key={question.accordionId}
id={question.accordionId}
expanded={expanded === question.accordionId}
onChange={handleChange(question.accordionId)}>
// ... your accordion content
</Accordion>
))}

最新更新