javascript - 如何使用反应检查元素是否存在?
问题描述
如何使用 React 检查 DOM 中是否存在元素?
当项目为 0 并且用户单击按钮时,我会在整个应用程序中显示一个弹出窗口。它由包装在 App 组件周围的上下文提供程序创建。
有一个添加按钮显示在某些页面“/items”中。
const root = () => {
<PopupContextProvider>
<App/>
</PopupContextProvider>
}
export const PopupContextProvider = ({ children }: any) => {
return (
<popupContext.Provider value={context}>
{children}
{(condition1 || condition2) && (
<Popup onHide={dismiss} />
)}
</popupContext.Provider>
);
}
function App() {
return (
<Route path="/items">
<Drawer/>
/>
//other routes
);
}
function Drawer() {
return (
<ButtonElement/> //this is a styled div component and i want to check if this element is
//present in dom at the sametime when popup is there in dom
);
}
我想做的事?
我想检查 ButtonElement 是否与弹出窗口同时存在于 DOM 中。
我想过的方法:
- 向按钮元素添加一个 id 并检查它是否存在使用
document.getelementbyid
(对我来说是最后一个选项) - 使用
ref
,但我不知道该怎么做
我想对按钮元素使用 ref,但我不知道如何将它传递给上下文。
最好的方法是什么?
解决方案
使用useRef
钩子并将其传递给子组件。这将是未定义的
假设你在const popupContext = React.createContext(undefined);
某个地方定义,大致这应该有效:
const PopupContextProvider = ({ children }: any) => {
const popupRef = useRef(null);
return (
<popupContext.Provider value={popupRef}>
{children}
{(condition1 || condition2) && (
<Popup onHide={dismiss} ref={popupRef}/>
)}
</popupContext.Provider>
);
}
const Drawer = () => {
return (
<popupContext.Consumer>
{value => (value !== undefined)
? <ButtonElement popup={true}/>
: <ButtonElement/>
}
</popupContext.Consumer>
);
}
有关上下文使用的更多信息:https ://reactjs.org/docs/context.html#reactcreatecontext
推荐阅读
- javascript - Google Charts - 组织结构图出现损坏
- node.js - 为什么 cron 作业会导致 Node.js pupeeter schdule 中的备忘录泄漏?
- azure - 使用 Runbook 删除 Azure 虚拟机规模集实例
- xml - 如何使用 XSLT 比较两个 XML 节点
- jquery - jquery在加载时改变类
- mysql - 删除 MySQL 中的 null 值并将非 null 值合并到一个单元格中
- sql-server - SQL Server 从阻塞会话链中获取主/父阻塞会话 ID
- javascript - 手动关闭 AntD 菜单
- ios - 通过创建三个 xib 文件水平滑动 TableView 或 CollectionView
- php - 使用外部类库作为 Laravel 的模型类