ReactJS将'JS代码作为文本'和真正的JS代码混淆:在ReactJS div中添加javascript代码作为文本

时间:2015-09-30 08:21:54

标签: javascript reactjs

我有一个反应JS组件,我想在div中输入一些示例JS代码作为文本。

代码看起来像这种东西

render: function() {
return ( 
   <div id="sample_code_text">
       <p>
         if( 1==1 ) {
                              console.log(50) ;
         }
       </p>
    </div>
)};

我在console.log上遇到错误(50);

 Uncaught Error: Parse Error: Line 37: Unexpected token ;

React的div将“代码作为文本”混淆为JS代码。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

你可以这样使用ES6 template strings

render: function() {
    var a = 10;
    return ( 
        <div id="sample_code_text">
            <p>
                {`
                    if (1 == 1) {
                       console.log(10);
                    }
                `}
            </p>
        </div>
    )
}

Example

或使用{ '{' }because now there is no solution to easy escape {}

的解决方案解决方案
render: function() {
    var a = 10;
    return ( 
        <div id="sample_code_text">
            <p>
                if (1 == 1) { '{' }
                   console.log(10);
                { '}' }
            </p>
        </div>
    )
}

Example

答案 1 :(得分:1)

我认为你要找的是@ dev-null 试试这个:

    <p>
      if( 1==1 ) {'{'}
        console.log(50) ;
      {'}'}
    </p>