[英]Return DOM element in render function of React component
I have an external library that renders some custom js controls.我有一个呈现一些自定义 js 控件的外部库。 The library returns a DOM element that can be inserted in to the page.
该库返回一个可以插入到页面中的 DOM 元素。
I am creating wrapper for this library in React.我正在 React 中为这个库创建包装器。 I have it all wired up except I'm not sure how to allow the render function to accept the DOM element as its return
除了我不确定如何允许渲染函数接受 DOM 元素作为它的返回之外,我已经把它全部连接起来了
render() {
if (this.state.someType) {
let customControl = new this.state.someType();
var node = customControl.getNode();
return node; //This is an HTMLDOMElement i.e. div or span
}
return <div>Loading Custom Control...</div>;
}
I am able to debug the code and everything is working properly.我能够调试代码并且一切正常。 The node is what I expect but the html on the page is never replaced.
该节点是我所期望的,但页面上的 html 永远不会被替换。
Here's a simple example.这是一个简单的例子。
render() {
const newNode = document.createElement('p');
return <div ref={(nodeElement) => {nodeElement && nodeElement.appendChild(newNode)}}/>
}
Render a normal JSX div
.渲染一个普通的 JSX
div
。 Use ref
inside.在里面使用
ref
。
Inside the ref
callback use .appendChild(node)
在
ref
回调中使用.appendChild(node)
See https://reactjs.org/docs/refs-and-the-dom.html见https://reactjs.org/docs/refs-and-the-dom.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.