[英]React.js Component children to DOM element
我正在尝试创建自己的地图组件,其中一项任务是创建自定义地图注释。 这是渲染函数中MapAnnotation
组件的样子
<MapAnnotation title='Annotation' latitude={ 12.345678 } longitude={ 12.345678 }>
<div style={{width: '100px', height: '100px', backgroundColor: 'lightblue'}} />
</MapAnnotation>
将MapAnnotation
组件转换为地图对象的方法非常简单:
createAnnotation(child) {
const { latitude, longitude, title } = child.props
var coordinate = new global.mapkit.Coordinate(latitude, longitude)
if ('children' in child.props) {
var newAnnotation = new global.mapkit.Annotation(coordinate, function(coordinate, options) {
var domElement =
return ReactDOMServer.renderToString(<div>{child.props.children}</div>)
}, { title: title })
return newAnnotation
} else {
var newAnnotation = new global.mapkit.MarkerAnnotation(coordinate, { title: title })
return newAnnotation
}
}
不幸的是,我不知道如何从 MapAnnotation 中存在的子级返回 DOM 元素。 现在我收到错误:
错误:[MapKit] 注释元素工厂必须返回一个 DOM 元素,得到
<div data-reactroot=""><div style="width:100px;height:100px;background-color:lightblue"></div></div>
代替。
我是 React.js 初学者,我的大部分知识来自 ReactNative。 这就是为什么我不知道谷歌大叔找到解决方案的关键字是什么的原因。
我很乐意提供帮助:)
基于博伊科夫答案的解决方案:
var domElement = document.createElement("div")
domElement.innerHTML = ReactDOMServer.renderToString(child.props.children)
return domElement
我想我可以使用 useRef 来做到这一点。
import react,{useRef, useEffect} from 'react';
const Test = ({book_id, chart_id, title, data_source}) => {
const refCom = useRef(null);
useEffect(() => {
if (refCom && refCom?.current) {
//Run the code you want to do inside.
console.log(refCom.current);
}
}, [refCom]);
return (<div ref={refCom}>....</div>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.