简体   繁体   English

如何将 React 组件渲染到主 App 组件中/

[英]How do I render a React component into the main App component/

I'm in the process of moving my client-side code from jQuery to React.我正在将我的客户端代码从 jQuery 移动到 React。 My (trimmed) main app looks like this我的(修剪过的)主应用程序看起来像这样

export const MyApp: FC = () => {
return <HashRouter>
    <SideNav {...data} />
    <Switch>
        <Route exact path="/" component={Dashboard} />
    </Switch>
</HashRouter>
}

And inside several components I sometimes need to call functions that build React components.在几个组件中,我有时需要调用构建 React 组件的函数。 Such as

export async function openDialog(recordId?: number) {
const elem = document.createElement('div');
elem.style.display = 'contents';
ReactDOM.render(<ConfigProvider>
    <Modal
        visible recordId={recordId} 
        onCancel={() => {
            ReactDOM.unmountComponentAtNode(elem);
            document.body.removeChild(elem);
        }} 
    />
</ConfigProvider>, elem);
document.body.appendChild(elem);
}

Problem is, that if in my Modal I have a react-router Link , then I get the following error:问题是,如果在我的Modal中我有一个 react-router Link ,那么我会收到以下错误:

Uncaught Error: Invariant failed You should not use Link outside a Router Uncaught Error: Invariant failed 你不应该在路由器外使用 Link

Now, I could understand the error, because I'm rendering outside the context of the MyApp .现在,我可以理解错误了,因为我在MyApp的上下文之外进行渲染。 My question is: How can I change my function so it does render into the same context of MyApp ?我的问题是:如何更改我的 function 使其呈现到与MyApp相同的上下文中?

I was not able to find any such question or concept online (aside of rewriting my whole app to use a state for each window I need to open, which is not practical at the moment).我无法在网上找到任何此类问题或概念(除了重写我的整个应用程序以对我需要打开的每个 window 使用 state 之外,目前这不实用)。

Thanks!谢谢!

The components which use router links must be children of components rendered inside a router.使用路由器链接的组件必须是在路由器内渲染的组件的子组件。

In your case, you only have <Dashboard /> and <SideNav /> rendered inside your router.在您的情况下,您的路由器内只有<Dashboard /><SideNav />呈现。 Make sure that <Modal / > is rendered by <Dashboard /> , <SideNav /> , or a descendant of them.确保<Modal / ><Dashboard /><SideNav />或它们的后代呈现。

You also manipulate DOM elements directly and this is not good practice with React.您还可以直接操作 DOM 元素,这不是 React 的好习惯。 You could run into confusing bugs as React will not recognize changes to the DOM您可能会遇到令人困惑的错误,因为 React 无法识别对 DOM 的更改

See: https://reactjs.org/docs/integrating-with-other-libraries.html参见: https://reactjs.org/docs/integrating-with-other-libraries.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM