如何消除ReactMarkdown中‘请使用components替代renderers’的警告?
解决ReactMarkdown中
renderers替换为components的警告问题 ReactMarkdown新版本已废弃renderers属性,改用components属性定义自定义渲染组件,这就是你看到警告的原因。按以下步骤修改代码即可消除警告:
1. 调整自定义渲染组件的定义
把原来的customRenderers改成符合components规范的写法,段落对应的键为p(对应HTML的<p>标签),同时调整参数解构方式:
const customComponents = { p: ({ node, children }) => { // 检查当前段落的第一个子元素是否为图片 if (node.children[0]?.type === 'image') { const image = node.children[0]; return ( <div className={classes.image}> <Image src={`/images/posts/${posts.slug}/${image.url}`} alt={image.alt} width={649} height={249} /> </div> ); } // 非图片段落保持默认渲染 return <p>{children}</p>; } };
2. 更新ReactMarkdown组件的属性
将renderers替换为components:
<ReactMarkdown components={customComponents}>{posts.content}</ReactMarkdown>
额外说明
添加?.可选链操作符是为了避免段落为空或第一个子元素不存在时触发报错,让代码更健壮。
内容的提问来源于stack exchange,提问作者RajGopalbh4
相关产品推荐
相关产品推荐

