【问题标题】:Force React component that have not mounted to DOM render?强制尚未安装到 DOM 渲染的 React 组件?
【发布时间】:2020-10-17 10:36:17
【问题描述】:

我有一个类是 React 的一个组件。如何强制该类渲染并返回给我一个 DOM 元素?

例如:

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(...);

我想让那个 DOM 元素对那个 DOM 元素执行自定义挂载(或任何我想要的),因为我的函数的结果是我希望类似于document.createElement() 的结果。

另一个作为真实用例的例子:

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

【问题讨论】:

标签: javascript reactjs dom


【解决方案1】:

我可能想太多了。它作为react-dom的API提供:render

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

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 2018-12-02
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2015-11-03
    • 2020-11-04
    • 2020-03-30
    相关资源
    最近更新 更多