Gatsby项目中渲染Contentful富文本时如何获取有序列表的项索引
解决方案
你当前的写法只覆盖了LIST_ITEM节点的渲染逻辑,而列表项的索引属于上层ORDERED_LIST节点的子节点顺序属性,LIST_ITEM的渲染回调默认不会携带父级数组的索引参数,所以无法直接拿到编号。
你只需要重写有序列表节点的渲染逻辑,自行遍历子节点即可直接获取索引:
import { BLOCKS } from "@contentful/rich-text-types"; import { renderRichText } from "gatsby-source-contentful/rich-text"; const options = { renderNode: { // 覆盖有序列表的默认渲染,不输出ol标签 [BLOCKS.ORDERED_LIST]: (node) => { // 遍历有序列表下的所有列表项,直接拿到索引 return node.content.map((listItem, index) => { // 渲染列表项内部的内容 const itemInnerContent = renderRichText(listItem, { ...options, renderNode: { ...options.renderNode, // 覆盖列表项默认渲染,不输出li标签,直接返回内部内容 [BLOCKS.LIST_ITEM]: (_, children) => children } }) return ( <div key={index} className="single-instruction"> <header> <p>Step {index + 1}</p> <div></div> </header> {itemInnerContent} </div> ) }) }, }, }; renderRichText(instructions, options)
如果你的富文本中存在嵌套有序列表的需求,只需在上述逻辑中加入节点层级判断即可适配。
内容的提问来源于stack exchange,提问作者Original BBQ Sauce
相关产品推荐
相关产品推荐

