问题
使用React-Markdown,我可以充分利用我的定制组件。但这是在markdown中使用了特定的预先构建的关键字。比如段落或图片。这很好用。但问题是,这些似乎都是预先构建的单词/条件,如段落、标题或图像。
我找不到一种方法来在我的标记中添加一些新的关键字,比如"CustomComponent“。这就是我现在所需要的,><
对于我来说,这可以很好地将markdown的图像转换为我在其他地方制作的自定义“页脚”组件。我知道这很可笑,但它是有效的。但我不知道如何让这个渲染器接受/创建一个新的关键字,如"emoji“、"customComponent”或"somethingSilly“。
let body =
``;
const renderers = {
image: () => <Footer/>
};
<ReactMarkdown source={body} renderers={renderers} />;我以前做过的一些工作:
一些文档:https://reposhub.com/react/miscellaneous/rexxars-react-markdown.html https://github.com/rexxars/commonmark-react-renderer/blob/master/src/commonmark-react-renderer.js#L50
示例:https://codesandbox.io/s/react-markdown-with-custom-renderers-961l3?from-embed=&file=/src/App.js
但是没有任何说明我如何使用"CustomComponent“来指示注入自定义组件。
用例/背景
我正在尝试从我的数据库中检索一篇格式类似于markdown的文章(基本上是一个巨大的字符串)。我将常规的react与typescript和redux一起使用--这是我的应用程序中唯一需要它的部分。
"
# Title
## Here is a subtitle
Some text
<CustomComponentIMade/>
Even more text after.
<CustomComponentIMade/>
"发布于 2021-06-23 18:32:58
我知道对于您的目的来说可能有点晚了,但我已经设法使用自定义备注组件解决了这个问题。
本质上,您还需要使用remark-directive插件as a small custom remark plugin (我直接从remark-directive文档中获得了这个插件)
然后在react markdown中,你可以指定插件,定制渲染器和定制标签。
import React from 'react'
import ReactMarkdown from 'react-markdown'
import {render} from 'react-dom'
import directive from 'remark-directive'
import { MyCustomComponent } from './MyCustomComponent'
import { visit } from "unist-util-visit"
import { h } from "hastscript/html.js"
// react markdown components list
const components = {
image: () => <Footer/>,
myTag: MyCustomComponent
}
// remark plugin to add a custom tag to the AST
function htmlDirectives() {
return transform
function transform(tree) {
visit(tree, ['textDirective', 'leafDirective', 'containerDirective'], ondirective)
}
function ondirective(node) {
var data = node.data || (node.data = {})
var hast = h(node.name, node.attributes)
data.hName = hast.tagname
data.hProperties = hast.properties
}
}
render(
<ReactMarkdown components={components} remarkPlugins={[directive, htmlDirectives]}>
Some markdown with a :myTag[custom directive]{title="My custom tag"}
</ReactMarkdown>,
document.body
)因此,在标记中,只要有像:myTag[...]{...attributes}这样的东西,就应该用attributes作为道具来呈现MyCustomComponent。
很抱歉我还没有测试代码,但希望它能传达出事情的要点,如果你需要一个工作示例,请让我知道,我会尽我最大的努力来设置一个。
https://stackoverflow.com/questions/66763417
复制相似问题