使用npm install notice-org/next安裝我們的包
import { NTC, NTCFragment, Notice } from "@notice-org/next";
interface Props {
notice: NTCFragment;
}
export default function Page({ notice }: Props) {
return <Notice fragment={notice} />;
}
export async function getServerSideProps() {
const notice = await NTC.fragment({ pageId: "{{{project}}}" });
return {
props: {
notice,
},
};
}
就是這樣,您已經準備就緒!
如果您需要更細粒度,例如製作自己的渲染,我們為您提供了支持。
1. 在getServerSideProps中獲取元素列表
export async function getServerSideProps(ctx: any) {
const md = await NTC.markdown({ pageId: ctx.query.id });
const head = await NTC.head({ pageId: ctx.query.id });
return {
props: {
article: md,
head,
},
};
}
2. 創建一個函數,將JSON列表中的每個元素轉換為React元素。
function createHeadElements(head: NTCWebElement[]) {
const heads: DOMElement<any, Element>[] = [];
for (let elem of head) {
let element;
if (elem.innerHTML) {
element = React.createElement(elem.tagName, {
...elem.attributes,
dangerouslySetInnerHTML: { __html: elem.innerHTML },
});
} else if (elem.innerText) {
element = React.createElement(elem.tagName, elem.attributes, [elem.innerText]);
} else {
element = React.createElement(elem.tagName, elem.attributes);
}
heads.push(element);
}
return heads;
}
3. 在useMemo中調用該函數,並將您的元素放在NestJS <Head />中
export default function Article({ article, head }: { article: string; head: NTCWebElement[] }) {
const content = useMemo(() => marked.parse(article) as string, [article]);
const headElements = useMemo(() => createHeadElements(head), [head]);
return (
<>
<Head>
{...headElements}
</Head>
<div className="article" dangerouslySetInnerHTML={{ __html: content }}></div>
</>
);
}