我有一个按钮,管理页面上组件的外观。它在桌面上工作得很好,但在平板电脑或移动设备中,没有什么能工作,useState似乎无法更新状态。
有人能向我解释一下为什么会发生这种事吗?
请参阅代码片段以供参考。我所指的组件是代码片段底部的联系人,谢谢。
const Conciergerie = () => {
const scrollToConciergerie = () => {
window.scrollTo({
top: 1200,
behavior: "smooth",
});
};
const [showform, setshowform] = useState(false);
useEffect(() => {
window.addEventListener("load", scrollToConciergerie);
return () => {
window.removeEventListener("load", scrollToConciergerie);
}
});
return (
<div className="section" onLoad={scrollToConciergerie}>
<div className="container">
<div className="text-center">
<h1 className=" my-4 text-capitalize" id="conciergerie">
Conciergerie
</h1>
</div>
<h3 className="text-capitalize concierge-subheading mt-3">
¿QUÉ NECESITAS?
</h3>
<p className="lead concierge-subheading-text">
</p>
</div>
<div className="container">
<div className="row text-center mt-5">
{conciergerieData.map((item) => {
return (
<div className="col-md-4" key={item.id}>
<span className="fa-stack fa-4x">
<Image
layout="fill"
src={item.icon}
alt=""
className="svg-inline--fa fa-solid fa-stack-1x fa-inverse"
aria-hidden="true"
focusable="false"
data-prefix="fas"
data-icon="house"
role="img"
/>
</span>
<h4 className="my-3 text-hogar2 text-uppercase">
{item.title}
</h4>
<ul>
{item.text.map((text) => {
return (
<li key={text.id} className="list-unstyled">
<p className="m-0 text-muted text-list">
{text.content}
</p>
</li>
);
})}
</ul>
{item.id === "algomas" ? (
<AiOutlinePlus
onClick={() => {
setshowform( !showform)
console.log(showform)
}}
className="fs-2"
fill="#5ab4ab"
/>
) : null}
</div>
);
})}
</div>
</div>
<div className={showform ?"algoma" : "d-none"}>
<Contact />
</div>
</div>
);
};
export default Conciergerie;发布于 2022-04-15 19:48:48
我相信钩子是在React 16.8中引入的,我看到你指的是React 16.6.3。我可能错了,但你为什么要用旧版的“反应”呢?
然后,我不确定你是否从你的useEffect得到了想要的结果。没有提供依赖数组,这意味着您的效果将在每个呈现上运行。这就是你的意图吗?
const [showform, setshowform] = useState(false);
const scrollToConciergerie = useCallback(() => {
window.scrollTo({
top: 1200,
behavior: "smooth",
});
}, []);
useEffect(() => {
window.addEventListener("load", scrollToConciergerie);
return () => {
window.removeEventListener("load", scrollToConciergerie);
}
}, [scrollToConciergerie]);这将确保只有在组件挂载时才运行效果,并将在卸载时删除事件侦听器。
既然你的问题是关于状态不像预期的那样工作,我发现了一些可能是原因的东西。虽然不确定,但值得一试。
当您想切换状态下的布尔值时,可以向setState提供一个函数,如下所示:
setshowform(currentValue => !currentValue)我不确定我的任何建议能解决你的问题,但如果你愿意的话,你可以试试。
发布于 2022-04-15 19:55:46
问题与div有关,该div的子节点位于按钮的同一级别上。乍看之下,它并不是visibile,但在使用dev工具并在其上方盘旋时,问题元素被突出显示。我只需设置div的宽度以适应内容以修复问题。
https://stackoverflow.com/questions/71887563
复制相似问题