0

我正在尝试在 React JS 应用程序上显示代码片段。为此,我有一组使用fetchAPI 获得的片段。

为此,我将必要的信息存储在一个数组中,然后使用该方法创建Snippet对象。Array::map

但是,当我尝试显示这些片段时,我发现Snippet's CSS 未正确应用。问题似乎是fetch通话延迟。如果不执行这些调用,一切正常。

一些注意事项: - 为了找到罪魁祸首,我对代码片段的参数进行了硬编码。- 为了获得 MWE,我用调用替换了对fetchAPI 的调用sleep - 如果我删除对 的调用sleep,则片段将正确呈现。

这是我负责类的代码:

import React, { Component } from 'react';
import { Container } from 'react-bootstrap';
import Snippet from './Snippet';

export default class Examples extends Component {
  constructor(props) {
    super(props);
    this.state = { snippets: [] };
  }

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  createSnippets = async () => {
    const snippets = [{ code: "int main(void)\n{\n  bool testing = true;\n}" }];

    await this.sleep(2000);

    return snippets;
  };

  componentDidMount() {
    this.createSnippets()
      .then(snippets => { this.setState({ snippets: snippets }); });
  }

  render() {
    const snippets = this.state.snippets;

    return (
      snippets.map((snippet) => {
        return (
          <div>
            <Container>
              <Snippet key={ "test" }
                title={ "test" }
                code={ snippet.code }
                language={ "cpp" }
                plugins={ ["line-numbers"] } />
            </Container>
          </div>
        );
      }
      )
    );
  }
};

不正确的结果如下所示不好

这是预期的结果:预期的

我正在使用prismjs来突出显示片段。这是我的实现:

import React, { Component } from 'react';
import { Container } from 'react-bootstrap';
import Prism from "prismjs";
import 'prismjs/components/prism-c';
import 'prismjs/components/prism-cpp';

import "prismjs/themes/prism-okaidia.css";


export default class Snippet extends Component {
  highlight = () => {
    if (this.ref && this.ref.current) {
      Prism.highlightElement(this.ref.current);
    }
  };

  render() {
    const title = this.props.title;
    const plugins = this.props.plugins;
    const code = this.props.code;
    const language = this.props.language;

    console.log("Snippet: title: %s, plugins: %s, code: %s, language: %s", title, plugins, code, language);

    return (
      <div key={ title }>
        <Container>
          <pre className={ !plugins ? "" : plugins.join(" ") }>
            <code title={ title } ref={ this.ref } className={ `language-${language}` }>
              { code }
            </code>
          </pre>
        </Container>
      </div>
    );
  };
}

我添加了console.log语句以查看属性是否设置正确,这两种情况似乎都是如此。

4

0 回答 0