问题描述
所以我试图在Gatbsy中使用PrismJS来显示我的代码块。我按照本教程进行了设置和运行,以下是我代码中的实现:
import React from "react";
import { useEffect } from "react";
import { graphql,Link } from 'gatsby';
import Layout from "../components/layout";
import SEO from "../components/seo";
//import the Prism package
import Prism from "prismjs"
const PostPage = ({ data }) => {
const { post } = data.gcms;
useEffect(() => {
// call the highlightAll() function to style our code blocks
Prism.highlightAll();
});
return (
<Layout>
<SEO
keywords={[
`planflow`,`ui`,`ux`,`information architecture`,]}
title={post.title}
/>
<section className="w-full text-gray-700 body-font">
<div className="container flex flex-col justify-center px-5 pb-24 mx-auto">
<h1 className="flex justify-center mb-12 text-4xl font-semibold text-center text-black">{post.title}</h1>
<div className="flex flex-col justify-center">
<div className="h-64 overflow-hidden rounded-lg border-1 border-gray-light">
<img alt="content" className="object-cover object-center w-full h-full" src={post.coverImage.url}></img>
</div>
<div className="flex flex-row justify-between w-full mt-4">
<span className="flex flex-col pl-8 mt-6">
<h3 className="text-2xl">{post.author.name}</h3>
<h4 className="text-black-lighter">Published: {post.date}</h4>
</span>
<span className="pr-8 mt-6">
{
post.tags.map((tag) =>
<span key={tag} className="inline-block px-3 py-1 mb-2 mr-2 text-xs font-medium tracking-widest capitalize border-2 border-dashed rounded border-black-lighter text-blue bg-blue-indigo">{tag}</span>
)
}
</span>
</div>
<div className="flex flex-col mt-6 sm:flex-row">
{/* <div>Notication Section Here.</div> */}
{/* {Post Content} */}
<div className="pt-4 mt-4 text-center border-t border-gray-300 sm:w-full sm:pl-8 sm:py-8 sm:border-t-0 sm:mt-0 sm:text-left">
<div dangerouslySetInnerHTML={{ __html: post.content.html }} className="mb-4 text-lg leading-loose sm:pr-8"></div>
</div>
</div>
</div>
</div>
</section>
</Layout>
)};
export const pageQuery = graphql`
query postPageQuery($id: ID!) {
gcms {
post(where: { id: $id }) {
id
html
}
}`
HTML内是相关的代码块,我认为应该由Prism检测到。最终,Prism似乎无法检测到它,并且代码没有运行。
在此提出任何建议。
谢谢!
解决方法
在 class
标签的 code
属性中包含 Prism 所需的语言以突出显示
在您的内容 html(您要解析的那个)中,确保您在 class
标签中设置 code
属性以指定使用的语言。
不要在要解析的 html 中使用 className
。 class
是 html 元素 <code class='language-javascript'></code>
中的一个属性。
而另一方面,.className
是一个属性,可以通过调用元素来获取/设置其类。
var element = document.createElement('code');
element.className = 'language-javascript'
// element is <span class='language-javascript'></span>
<pre>
<code class=”language-javascript”>
<p>some text</p>
</code>
</pre>