简体   繁体   English

强制尚未安装到 DOM 渲染的 React 组件?

[英]Force React component that have not mounted to DOM render?

I have a class that's a component of React.我有一个 class,它是 React 的一个组件。 How can I force that class render and return to me a DOM element?如何强制 class 呈现并返回给我一个 DOM 元素?

For example:例如:

class MyComponent extends React.Component{...}
const myVirtualDOMComponentButNotMountToAnywhere = <MyComponent {...someprops} />

// is there any function that
const myDOMElement = MyComponent.createDOMElement();
// or
const myDOMElement = myVirtualDOMComponentButNotMountToAnywhere.renderAsDOMElement();
// return a result that similar to
document.createElement(...);

I want to get that DOM element to perform custom mount (or what ever I want to) to that DOM element as the result from my function I expect that similar to the result of document.createElement() .作为我的 function 的结果,我希望该 DOM 元素对该 DOM 元素执行自定义安装(或我想要的任何操作),我希望这类似于document.createElement()的结果。

For another example as a real usecase:另一个作为真实用例的例子:

import { Link } from 'react-router-dom';
const myLink = <Link to='/...' />
const myDOMLink = myLink.renderAsDOMElement();
document.getElementById('someId').appendChild(myDOMLink);

I may was too overthinking.可能是我想太多了。 It was provided as an API of react-dom : render它是作为react-dom的 API 提供的: render

import ReactDOM from 'react-dom';
ReactDOM.render(<MyComponent />, document.getElementById('someId'))

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

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