如何使用React获取WordPress API并保留完整样式(而非仅纯文本)
别担心,这个问题非常常见,核心原因是你没正确处理WordPress API返回的HTML内容,也没按需获取媒体资源。我给你一步步拆解解决方案:
1. 先确保拿到WordPress渲染后的HTML内容
WordPress REST API返回的文章内容默认有两个版本:
content.raw:原始未格式化的纯文本(就是你现在拿到的内容)content.rendered:已经包含<h1>、<p>、<img>等所有HTML标签的渲染后内容
所以请求文章时,一定要提取content.rendered字段。举个fetch请求的例子:
// 请求WordPress文章列表 fetch('https://你的WordPress站点域名/wp-json/wp/v2/posts') .then(res => res.json()) .then(posts => { const processedPosts = posts.map(post => ({ id: post.id, title: post.title.rendered, // 标题也要拿rendered版本,避免纯文本 content: post.content.rendered, featuredImageId: post.featured_media })); // 把处理好的文章数据存到React state里 setPosts(processedPosts); });
2. 在React中正确解析HTML内容
React默认会转义所有HTML字符串,直接输出的话会把<h1>这类标签当成纯文本显示。你需要用dangerouslySetInnerHTML告诉React直接解析HTML:
// 单篇文章的渲染组件 function Post({ post }) { return ( <div className="post-container"> {/* 渲染标题 */} <h1 dangerouslySetInnerHTML={{ __html: post.title }} /> {/* 渲染文章内容 */} <div className="post-content" dangerouslySetInnerHTML={{ __html: post.content }} /> </div> ); }
⚠️ 小提醒:dangerouslySetInnerHTML带"dangerously"是有原因的——如果你的WordPress允许用户提交自定义HTML,可能存在XSS风险。如果是自己管理的站点,风险很低;如果是开放站点,建议用dompurify过滤后再渲染:
import DOMPurify from 'dompurify'; // 先净化HTML内容 const cleanContent = DOMPurify.sanitize(post.content); // 再渲染 <div dangerouslySetInnerHTML={{ __html: cleanContent }} />
3. 解决图片不显示的问题
图片无法加载通常有两个原因,对应两种解决办法:
原因1:图片路径是相对路径
WordPress返回的HTML里,<img>的src可能是相对路径(比如/wp-content/uploads/2024/05/photo.jpg),如果你的React项目和WordPress不在同一个域名下,浏览器会把这个路径解析成React站点的域名,导致404。
写个工具函数补全域名即可:
function fixImagePaths(html, wpSiteUrl) { // 替换所有/wp-content开头的相对路径 return html.replace(/src="\/wp-content\//g, `src="${wpSiteUrl}/wp-content/`); } // 使用示例 const processedContent = fixImagePaths(post.content, 'https://你的WordPress站点域名');
原因2:特色图片只拿到ID,没拿到URL
WordPress API默认只返回特色图片的ID,不会直接返回图片地址。你可以在请求时加上_embed参数,让API把特色图片的信息嵌进来:
// 加上_embed参数请求文章 fetch('https://你的WordPress站点域名/wp-json/wp/v2/posts?_embed') .then(res => res.json()) .then(posts => { const processedPosts = posts.map(post => ({ ...post, // 提取特色图片的URL featuredImageUrl: post._embedded?.['wp:featuredmedia']?.[0]?.source_url || '' })); setPosts(processedPosts); });
然后在组件里直接渲染特色图片:
{post.featuredImageUrl && ( <img src={post.featuredImageUrl} alt={post.title.rendered} className="post-featured-image" /> )}
4. 补充:给内容加基础样式(可选)
如果你的WordPress主题有自定义排版样式(比如标题间距、段落行高),React渲染的HTML可能没有这些样式。你可以自己写CSS匹配,比如在index.css里添加:
.post-content h1 { font-size: 2rem; margin: 1.5rem 0; font-weight: 700; } .post-content p { line-height: 1.6; margin-bottom: 1rem; } .post-content img { max-width: 100%; height: auto; margin: 1rem 0; border-radius: 4px; }
这样渲染出来的内容就有舒服的排版了。
内容的提问来源于stack exchange,提问作者hegibo2346

