[英]React.js Component children to DOM element
I am trying to create my own Map component and one of the tasks is to create custom Map Annotation.我正在尝试创建自己的地图组件,其中一项任务是创建自定义地图注释。 This is how it looks like a
MapAnnotation
component in the render function这是渲染函数中
MapAnnotation
组件的样子
<MapAnnotation title='Annotation' latitude={ 12.345678 } longitude={ 12.345678 }>
<div style={{width: '100px', height: '100px', backgroundColor: 'lightblue'}} />
</MapAnnotation>
The method that converts MapAnnotation
component into the map object is pretty simple:将
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
}
}
Unfortunately, I do not know how to return the DOM element from children that exist in MapAnnotation.不幸的是,我不知道如何从 MapAnnotation 中存在的子级返回 DOM 元素。 Right now I am getting the error:
现在我收到错误:
Error: [MapKit] Annotation element factory must return a DOM element, got
<div data-reactroot=""><div style="width:100px;height:100px;background-color:lightblue"></div></div>
instead.错误:[MapKit] 注释元素工厂必须返回一个 DOM 元素,得到
<div data-reactroot=""><div style="width:100px;height:100px;background-color:lightblue"></div></div>
代替。
I am the React.js beginner and most of my knowledge I have from ReactNative.我是 React.js 初学者,我的大部分知识来自 ReactNative。 This is the reason why I do not know what is the keyword to find the solution with Uncle Google.
这就是为什么我不知道谷歌大叔找到解决方案的关键字是什么的原因。
I will be glad for help :)我很乐意提供帮助:)
The solution based on Boykov answer:基于博伊科夫答案的解决方案:
var domElement = document.createElement("div")
domElement.innerHTML = ReactDOMServer.renderToString(child.props.children)
return domElement
I think I can do it using useRef.我想我可以使用 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.