remarkjs - react-markdown 使用自定义组件时显示 div 而不是元素标签
问题描述
我正在尝试~the underlined text~
在 react-markdown ( remark )中编写一个自定义插件以支持下划线(使用语法),问题是结果使用div标签而不是ins。
这是插件:
const UNDERLINE_REGEX = /~(.*)~/g;
const extractPosition = (string, start, end) => {
const startLine = string.slice(0, start).split("\n");
const endLine = string.slice(0, end).split("\n");
return {
start: {
line: startLine.length,
column: startLine[startLine.length - 1].length + 1,
},
end: {
line: endLine.length,
column: endLine[endLine.length - 1].length + 1,
},
};
};
const extractText = (string, start, end) => ({
type: "text",
value: string.slice(start, end),
position: extractPosition(string, start, end),
});
const underlinePlugin = () => {
function transformer(tree) {
console.log(tree);
visit(tree, "text", (node, position, parent) => {
const definition = [];
let lastIndex = 0;
const matches = node.value.matchAll(UNDERLINE_REGEX);
for (const match of matches) {
const value = match[1];
const type = "underline";
const tagName = "ins";
if (match.index !== lastIndex) {
definition.push(
extractText(node.value, lastIndex, match.index)
);
}
definition.push({
type,
tagName,
children: [
extractText(
node.value,
match.index + 1, // 1 is start ~
match.index + value.length + 1 // 1 is start ~
),
],
position: extractPosition(
node.value,
match.index,
match.index + value.length + 2 // 2 is start and end ~
),
});
lastIndex = match.index + value.length + 2; // 2 is start and end ~
}
if (lastIndex !== node.value.length) {
const text = extractText(
node.value,
lastIndex,
node.value.length
);
definition.push(text);
}
const last = parent.children.slice(position + 1);
parent.children = parent.children.slice(0, position);
parent.children = parent.children.concat(definition);
parent.children = parent.children.concat(last);
});
}
return transformer;
};
这是 Markdown 的用法:
<ReactMarkdown
remarkPlugins={[plugin]}
components={{
ins: ({ value }) => <ins>{value}</ins>,
underline: ({ value }) => <ins>{value}</ins>,
}}>
~Hello~, **world**!
</ReactMarkdown>
这是结果
我用过type: 'underline'
, type: 'ins'
, tagName: 'underline'
, 'tagName: 'ins'
,但它们都不起作用。我不知道我在这里做错了什么。
感谢您的时间 :)
解决方案
remark markdown 处理器支持CommonMark 规范,该规范不包括对ins
ordel
标签的支持。react-markdown组件可能受CommonMark限制(为什么没有下划线?)。
推荐阅读
- python - 带有启动字符的蛮力哈希
- hangouts-api - 用于创建/更新消息的 Google Chat Rest api 不起作用?收到 500 内部服务器错误?
- datagridview - c# 使用 Datepicker 过滤绑定的 DatagridView
- xaml - 在 Xamarin 表单中的地图 Pin 图上添加动态内容
- json - JOLT - 使用示例和查询连接、移位和动态数组来接近 JSON 转换
- vue.js - 404 - 找不到文件或目录。vuejs 3 和 plesk
- r - SPSS Syntax to R 用于判别分析
- python - 获取每个输出文件的唯一名称 (docxtpl)
- list - 如何在 Scala 中对对象进行模式匹配
- c# - Windows Media Player 未在 KeyDown 事件中播放