Import html string on a different file on react.使用prismjs显示代码高亮

Import html string on a different file on react. Using prismjs to display code highlighting

使用 Prismjs 在设计系统中显示代码片段。

我想将 html 代码示例分离到一个独立文件中,然后将其导入到我的组件中。

代码示例组件:

CodeSampleContainer.jsx

import React, { Component } from 'react';
import Prism from "prismjs";
import './CodeSample.scss';
import '../Shared/prism.css';

// Import separate html file
import { html } './htmlSnippet.jsx';

class CodeSample extends Component {
  hasHtmlBlob() {
    return (
      <pre>
        <code className="language-html">
          {html} // Any html displayed here will be highlighted by prism
        </code>
      </pre>
      )
    }
  }

  render() {
    return (
      <div className="CodeSample"> 
        {this.hasHtmlBlob()}
      </div>
    )
  }
}

HTML 我要导出:

htmlSnippet.jsx

const html = `
  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>`

return html;

你的代码有两个问题:

JSX 语法

不要将模板声明为字符串,而应在 "react way"

上声明
const html = (
    <div>
        <ul>
           <li>1</li>
           <li>2</li>
           <li>3</li>
        </ul>
    </div>
);

导出缺失

如果您想从 htmlSnippet.jsx 中导出模板,您应该使用 export,而不是 return

export { html };