我正在尝试在 React JS 应用程序上显示代码片段。为此,我有一组使用fetch
API 获得的片段。
为此,我将必要的信息存储在一个数组中,然后使用该方法创建Snippet
对象。Array::map
但是,当我尝试显示这些片段时,我发现Snippet
's CSS 未正确应用。问题似乎是fetch
通话延迟。如果不执行这些调用,一切正常。
一些注意事项: - 为了找到罪魁祸首,我对代码片段的参数进行了硬编码。- 为了获得 MWE,我用调用替换了对fetch
API 的调用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
语句以查看属性是否设置正确,这两种情况似乎都是如此。