我有一些代码
let red = 'red'
let blue = 'blue'
let formula = "1+2"
let answer = "3"
let string = "<span class="+red+">"+formula+"</span>"+"="+"<span class="+blue+">"+answer+"</span>"
111 在渲染的回归中
<div dangerouslySetInnerHTML={{__html: string]}} >
以上将显示“1 + 23”没有颜色,但是,我想要1 + 2 = 3创建红色和蓝色类
UPDATE:我发现不应该是“className”,应该是“class”,即使这是在jsx中,我仍然无法得到相等的显示,实际上该类也来自一个字符串
答案 0 :(得分:1)
问题在于HTML字符串中的引号,将classes
括在单引号中,如
class App extends React.Component {
render() {
let formula = "1+2"
let answer = "3"
let string = "<span className='red'>"+formula+"</span>"+"="+"<span className='blue'>"+answer+"</span>"
return (
<div dangerouslySetInnerHTML={{__html: string}} ></div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<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="app"></div>