使用react-markdown获取h3标题文本报错,求解决方案
解决react-markdown获取h3标题时的filter报错问题
错误原因
你遇到的Uncaught TypeError: reactMarkdown.props.children.filter is not a function,本质是因为reactMarkdown.props.children是你传入的markdown字符串,并非可遍历的React元素数组,自然不存在filter方法。
两种正确实现方式
方式一:提前解析markdown字符串提取h3标题
借助remark-parse解析markdown语法树,再用unist-util-visit遍历节点筛选h3:
import { parse } from 'remark-parse'; import { visit } from 'unist-util-visit'; // 定义提取h3标题的函数 function getH3Titles(markdownContent) { const h3List = []; // 解析markdown为语法树 const astTree = parse(markdownContent); // 遍历所有heading节点 visit(astTree, 'heading', (node) => { // 筛选层级为3的标题 if (node.depth === 3) { // 拼接标题内的文本内容 const titleText = node.children.map(child => child.value).join(''); h3List.push(titleText); } }); return h3List; } // 使用示例 const sampleMarkdown = ` # 一级标题 ## 二级标题 ### 功能介绍 这是功能说明内容 ### 注意事项 这里是需要注意的点 `; const h3Titles = getH3Titles(sampleMarkdown); console.log(h3Titles); // 输出:["功能介绍", "注意事项"]
方式二:通过react-markdown的自定义renderer收集h3标题
在渲染markdown时,拦截h3元素的渲染逻辑,同步收集标题文本:
import React, { useState, useEffect } from 'react'; import ReactMarkdown from 'react-markdown'; import { parse } from 'remark-parse'; import { visit } from 'unist-util-visit'; function MarkdownRenderer({ markdown }) { const [collectedH3, setCollectedH3] = useState([]); // 监听markdown内容变化,重新收集h3标题 useEffect(() => { const tempH3 = []; const astTree = parse(markdown); visit(astTree, 'heading', (node) => { if (node.depth === 3) { tempH3.push(node.children.map(c => c.value).join('')); } }); setCollectedH3(tempH3); }, [markdown]); return ( <div> <ReactMarkdown>{markdown}</ReactMarkdown> <div className="h3-collector"> <h4>收集到的H3标题:</h4> <ul> {collectedH3.map((title, index) => ( <li key={index}>{title}</li> ))} </ul> </div> </div> ); }
补充说明
不要直接尝试操作reactMarkdown组件的props.children,react-markdown内部会将传入的字符串转为React元素,对外暴露的children就是原始markdown文本,不是渲染后的节点数组。
内容的提问来源于stack exchange,提问作者soccerway
相关产品推荐
相关产品推荐

