[英]How to programatically render a component in React 18
I did a function that creates a modal programatically for React 17, where you just needed to call a function to create a new modal.我做了一个 function,它以编程方式为 React 17 创建了一个模态,你只需要调用 function 来创建一个新的模态。
It was working fantastic before the ReactDOM.render was deprecated.在ReactDOM.render被弃用之前,它工作得非常好。
Is there a way to replace the render function with something else in React 18?有没有办法用 React 18 中的其他东西替换渲染 function? Right now the createRoot function is only for the root component, I want to render simple components in a specified DOM element.
现在createRoot function 仅适用于根组件,我想在指定的 DOM 元素中呈现简单的组件。
It worked like this:它是这样工作的:
app.jsx应用程序.jsx
<button onClick={() => createModal(<h1>I'm a component inside a modal</h1>)}>Open Modal</button>
It handles it's own state, very useful if you want to make a bunch of modals in seconds.它处理自己的 state,如果您想在几秒钟内制作一堆模态框,这非常有用。
This is the code:这是代码:
index.js => Here is the container. index.js => 这是容器。
import React from 'react'
import ReactDOM from 'react-dom'
import './index.scss'
import App from './App.jsx'
ReactDOM.render(
<React.StrictMode>
<div id="modal-container"></div> <- This is the container
<App />
</React.StrictMode>,
document.getElementById('root')
)
Modal/Modal.jsx => The modal component. Modal/Modal.jsx => 模态组件。
import { useState } from 'react'
import './Modal.scss'
const Modal = ({ content }) => {
const [isOpen, setIsOpen] = useState(true)
if (isOpen) {
return (<>
<div className="modal-background" onClick={() => setIsOpen(false)} />
<div className="modal-content" >
{content}
</div>
<button onClick={() => setIsOpen(false)} className="close-button" >Close</button>
</>)
} else return null
}
export default Modal
Modal/index.js => The call function: Modal/index.js => 调用 function:
import { render } from "react-dom"
import Modal from "./Modal"
const createModal = (content) => render(
<Modal key={Math.random()} content={content} />, document.getElementById("modal-container")
)
export default createModal
It worked using createRoot this way, instead of render:它以这种方式使用 createRoot 工作,而不是渲染:
Modal/index.js模态/index.js
import { createRoot } from 'react-dom/client'
import Modal from "./Modal"
const createModal = (content) => {
if (!window.modalContainer) {
window.modalContainer = createRoot(document.getElementById('modal-container'))
}
window.modalContainer.render(<Modal key={Math.random()} content={content} />)
}
export default createModal
It checks if createRoot on the specified component has been called before, so it only call createRoot once, and the render function any time a new modal is created.它检查指定组件上的 createRoot 之前是否已被调用过,因此它只调用一次 createRoot,并且在任何时候创建新模态时都会渲染 function。
If you have a better answer it would be awesome too.:)如果您有更好的答案,那也很棒。:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.