我正在将自定义 HTML 映射到我网站的一些降价元素。由于某种原因,在 中genId
,构建失败,因为 props 可以是空字符串/null。但是,这只发生在生产构建中,并且一切都在本地完美运行。
我还注意到,在刷新时,id全部丢失,而在从单独页面加载的初始页面时,它们存在。
此代码的目的是将数据从降价标题中取出并将其转换为 CSS ID。
成分
import postStyling from "../../styles/post/Index.module.css";
const genId = (props) => {
console.log(props);
if (props === undefined || props === "") return "";
return props.toLowerCase().replaceAll(" ", "_");
};
const MDXComponents = {
p: (props) => (
<p {...props} className={postStyling["content"]}>
{props.children}
</p>
),
h1: (props) => (
<h1
{...props}
id={genId(props.children)}
className={`${postStyling["main-heading"]}`}
>
{props.children}
</h1>
),
h2: (props) => (
<h2
{...props}
className={postStyling["post-header"]}
id={genId(props.children)}
>
{props.children}
</h2>
),
h3: (props) => (
<h3
{...props}
className={postStyling["post-header"]}
id={genId(props.children)}
>
{props.children}
</h3>
),
h4: (props) => (
<h4
{...props}
className={postStyling["post-header"]}
id={genId(props.children)}
>
{props.children}
</h4>
),
};
export default MDXComponents;
刷新同一页面
从主页单击
零件
import React, { useState, useEffect } from "react";
// Custom Components
import BlogHeader from "./BlogHeader";
import MDXComponents from "../mdx/MDXComponents";
import { MDXRemote } from "next-mdx-remote";
// CSS
import styles from "../../styles/admin/Panel.module.css";
import post from "../../styles/post/Index.module.css";
const PostTitle = ({ title, date }) => {
return (
<div className={post["title"]}>
<span>{title}</span>
<span className={post["date"]}>{date}</span>
</div>
);
};
const TableOfContents = ({ toc }) => {
return (
<div className={post["toc"]}>
<div dangerouslySetInnerHTML={{ __html: toc }}></div>
</div>
);
};
function Post({ content, metadata, toc }) {
let icon = metadata["type"] == "video" ? "" : "";
return (
<div className={styles.container}>
<BlogHeader />
<PostTitle title={`${icon} ${metadata.title}`} date={metadata.date} />
<h2 id={post["toc-header"]}>Table of Contents</h2>
<TableOfContents toc={toc} />
<MDXRemote {...content} components={MDXComponents} />
</div>
);
}
export default Post;