如何为降价中的标题提供自定义 ID?
How to give a custom id to a heading in markdown?
我正在使用 markdown to jsx
作为降价解析器。如何为降价中的标题提供自定义 ID?
### Generation of keys {#custom-id}
正在给予:
<h3 id="generation-of-keys-custom-id">Generation of keys {#key-generation}</h3>
但我想要:
<h3 id="custom-id">Generation of keys </h3>
您无法使用 markdown-to-jsx as it currently exists. You can change the ID by writing some custom slugify
function on the options
argument 执行此操作,但您将无法更改标题中的内容。
这里is the relevant code for how it creates Heading
components from JSX. Here is the Regular Expression用来解析标题:
/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/
可视化为
你可以看到他们捕获了两条信息:
- “级别”(又名
h1
到 h6
)
- 以及标题的正文
回到图书馆,在 _parse
函数中,我们 return 来自正则表达式匹配的 Object:
_parse(capture, parse, state) {
return {
content: parseInline(parse, capture[2], state),
id: options.slugify(capture[2]),
level: capture[1].length,
}
},
您可以看到他们使用 slugify
选项(具有合理的默认值)创建了 id
属性。这是您更改 ID 构成方式的机会。
但是,您可以看到 content
没有任何自定义空间。
库然后使用 _react
函数最终将解析的 object 转换为 JSX 节点:
_react(node, output, state) {
node.tag = `h${node.level}`;
return (
<node.tag id={node.id} key={state._key}>
{output(node.content, state)}
</node.tag>
)
},
我会考虑在存储库上打开一个 PR,它有一个使用一些 pre-defined 语法的第三个捕获组(可能使用 {#custom-id-here}
,就像你拥有的那样)。否则,您可以打开一个 PR 以提供另一个可选函数,该函数在将 content
传递给最终的 _react
调用之前对其进行转换。
我正在使用 markdown to jsx
作为降价解析器。如何为降价中的标题提供自定义 ID?
### Generation of keys {#custom-id}
正在给予:
<h3 id="generation-of-keys-custom-id">Generation of keys {#key-generation}</h3>
但我想要:
<h3 id="custom-id">Generation of keys </h3>
您无法使用 markdown-to-jsx as it currently exists. You can change the ID by writing some custom slugify
function on the options
argument 执行此操作,但您将无法更改标题中的内容。
这里is the relevant code for how it creates Heading
components from JSX. Here is the Regular Expression用来解析标题:
/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/
可视化为
你可以看到他们捕获了两条信息:
- “级别”(又名
h1
到h6
) - 以及标题的正文
回到图书馆,在 _parse
函数中,我们 return 来自正则表达式匹配的 Object:
_parse(capture, parse, state) {
return {
content: parseInline(parse, capture[2], state),
id: options.slugify(capture[2]),
level: capture[1].length,
}
},
您可以看到他们使用 slugify
选项(具有合理的默认值)创建了 id
属性。这是您更改 ID 构成方式的机会。
但是,您可以看到 content
没有任何自定义空间。
库然后使用 _react
函数最终将解析的 object 转换为 JSX 节点:
_react(node, output, state) {
node.tag = `h${node.level}`;
return (
<node.tag id={node.id} key={state._key}>
{output(node.content, state)}
</node.tag>
)
},
我会考虑在存储库上打开一个 PR,它有一个使用一些 pre-defined 语法的第三个捕获组(可能使用 {#custom-id-here}
,就像你拥有的那样)。否则,您可以打开一个 PR 以提供另一个可选函数,该函数在将 content
传递给最终的 _react
调用之前对其进行转换。