首页 > 解决方案 > 如何使用反应检查元素是否存在?

问题描述

如何使用 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 中。

我想过的方法:

我想对按钮元素使用 ref,但我不知道如何将它传递给上下文。

最好的方法是什么?

标签: javascriptreactjstypescript

解决方案


使用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


推荐阅读