我有一个 Next.js 应用程序(版本 13),其中包含几个使用 Tailwind CSS 设计样式的组件。然后,从使用 Node.js 用 React 编写的 CMS 系统中抓取这些组件,并使用
cheerio
进行清理。抓取后,生成的 HTML 内容将发送到 React 前端并使用 html-react-parser
库进行解析。
但是,我面临一个问题:即使 CSS 类完整保留,一些 Tailwind CSS 样式也没有应用在 React 应用程序中。当比较 Next.js 应用程序和 React CMS 中同一页面的显示时,这种不一致很明显。
1。 Next.js 组件:
// Catalog component
<section className='...'>
{cars.data?.map((car: Car) => (
<CarComponent key={car._id + ''} car={car} />
))}
</section>
// Car component
<div className='...' onClick={() => router.push(`${pathname}/${car._id}`)}>
<DetailsComponent car={car} />
</div>
// Details component
<div className='...'>
// Image and details here...
</div>
2。刮痧:
pageByUrl: async (_, { code }) => {
// Scraping and sanitizing logic here...
const html = await scrapeContent('http://localhost:3000' + url);
const page = sanitizeHTML(html);
return { page };
}
3. React 前端解析:
const EditableMain: FC = () => {
// Parsing and rendering logic...
const parsed = parse(page as string, options);
return <>{html}</>;
};
4。预期与现实: 鉴于类保持不变,我希望页面在 Next.js 应用程序和 React CMS 中看起来相同。但是,React CMS 版本中缺少某些 Tailwind CSS 样式。
5。支持证据: 我将提供两张屏幕截图进行比较:一张来自 Next.js 应用程序,一张来自 React CMS。这将展示样式上的差异。
解决方案: 主要挑战来自 EditableMain 组件,其中动态解析的 HTML 无法被 Tailwind CSS 识别:
const EditableMain: FC = () => {
// ...
useEffect(() => {
if (page) {
const parsed = parse(page as string, options);
setHtml(parsed as any);
}
}, [page]);
return <>{html}</>;
};
要点:
结论: Tailwind 不会轻易地将样式应用于尚未由 React 渲染的动态引入的类。确保所有必要的 Tailwind 类都被渲染(即使隐藏),以便在构建阶段被识别和保留。