在<code> tag with JSX

时间:2016-05-13 15:31:03

标签: javascript reactjs ecmascript-6 react-jsx

I am using React to render some UI components. I would like to display some JavaScript code inside of <code> tag. I've tried the following:

class A extends React.Component {
    render() {
        return(
            <pre><code>
                (function(a, b) {
                    var s = a.prop;
                    // ...
                }(c, d));
            </code></pre>
        );
    }
}

When I try to compile this script with webpack and Babel, I get an unexpected token error at the line var s = a.prop. How can I properly render this JavaScript?

1 个答案:

答案 0 :(得分:2)

@Pamblam是对的,你真的需要一个字符串:

  render() {
    var foo = `
      (function(a, b) {
        var s = a.prop;
        // ...
      }(c, d));
    `

    return (
      <pre>
        <code>{foo}</code>
      </pre>
    )
  }

<强> fiddle