我使用Leafet从应用程序中的较大地图组件中获取一个小组件,似乎不可能将JSX包含在Leafet DivIcon的html字符串中。
更大的地图组件渲染部分:
render () {
const {tobject, strings} = this.props
let circle = classes.redCircle
if (tobject.lastPoint.activeEvents.ignition) {
circle = classes.greenCircle
}
const icon = new window. L. DivIcon({
html:
` <div class= ${classes.tobjecticon}><span class= ${classes.tobjecticontext}><div class= ${circle}></div></span></div> `
})
新发布的组件StatusCircle.js:
import React from 'react'
import classes from './StatusCircle.scss'
export const StatusCircle = ({ status}) => {
let circle = classes.redCircle
if (status) {
circle = classes.greenCircle
}
return (
<div className={circle} ></div>
)
}
export default StatusCircle
我的问题与this one类似。我已经尝试了StatusCircle的 renderToString(),但是使用了ReactDOM(在那里已弃用)而不是ReactDOMServer并且它没有工作说没有这样的功能。是否可以使用ReactDOMServer.renderToString()或.renderToStaticMarkup()来实现这一点,或者最好在没有提取的情况下保持不变?
答案 0 :(得分:1)
将内部html留在父组件中是可以的。但是这里是在不使用ReactDOMServer
的情况下将其呈现为标记的方法。这有点棘手的方式=)
class Inner extends React.Component {
render () {
return (
<span {...this.props}>Inner Element</span>
)
}
}
class Outer extends React.Component {
render () {
const span = document.createElement('span');
ReactDOM.render(<Inner className="red" />, span);
//target html
console.log(span.innerHTML);
return (
<div>
You can use this html
<pre>
{span.innerHTML}
</pre>
</div>
)
}
}
ReactDOM.render(<Outer />, document.querySelector('#root'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
答案 1 :(得分:0)
我不想在项目中添加更多导入并依赖它们,但使用ReactDOM.Render instide render()给出:&#34;警告:_renderNewRootComponent():渲染方法应该是纯粹的道具和国家的功能;不允许从渲染中触发嵌套组件更新。如有必要,触发componentDidUpdate中的嵌套更新。检查StatusCircle&#34;的render方法。虽然ReactDOMServer.renderToStaticMarkup()完美地运作如下:
class App extends React.Component{
render() {
let greenCircle = ReactDOMServer.renderToStaticMarkup(<StatusCircle status={true} />)
console.log(greenCircle)
let redCircle = ReactDOMServer.renderToStaticMarkup(<StatusCircle status={false} />)
console.log(redCircle)
return (
<div>
<StatusCircle status={true} />
<StatusCircle status={false} />
</div>
)
}
}
const StatusCircle = ({status}) => {
let circle = "redCircle"
if (status) {
circle = "greenCircle"
}
return <div className={circle}></div>
}
ReactDOM.render(<App />, document.querySelector('#root'))
&#13;
.redCircle {
background-color: red;
border-radius: 50px;
width: 10px;
height: 10px;
margin: 10px;
}
.greenCircle {
background-color: green;
border-radius: 50px;
width: 10px;
height: 10px;
margin: 10px;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom-server.min.js"></script>
<div id="root"></div>
&#13;