微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React-Markdown 自定义组件声明,如何在渲染器中声明使用自定义组件?

如何解决React-Markdown 自定义组件声明,如何在渲染器中声明使用自定义组件?

问题

使用 React-Markdown,我可以完全使用我的自定义构建组件。但这是在降价中使用特定的预先构建的关键字。喜欢段落或图像。这非常有效。但问题是这些似乎都是预先构建的词/条件,如段落、标题或图像。

我找不到在 Markdown 中添加新关键字的方法,例如要使用的“CustomComponent”。这就是我现在需要的全部>

这对我来说很好用,可以将降价的图像变成我在其他地方制作的自定义“页脚”组件。我知道这很荒谬,但它有效。但我不知道如何让这个渲染器接受/创建一个新的关键字,比如“emoji”或“customComponent”或“somethingSilly”。

let body = 
    `![Fullstack React](https://dzxbosgk90qga.cloudfront.net/fit-in/504x658/n/20190131015240478_fullstack-react-cover-medium%402x.png)`;

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 类似(基本上是一个巨大的字符串)。我正在使用 typescript 和 redux 的常规反应——这是我的应用程序中唯一需要这个的部分。

"
# Title

## Here is a subtitle

Some text

<CustomComponentIMade/>

Even more text after.


<CustomComponentIMade/>

"

解决方法

我知道它很可能对您来说有点晚了,但我已经设法使用自定义备注组件解决了这个问题。

基本上,您还需要使用 remark-directive 插件as a small custom remark plugin(我直接从 remark-directive 文档中获得了这个插件)

然后在 react markdown 中,您可以为 eg 指定插件、自定义渲染器和自定义标签。

import React from 'react'
import ReactMarkdown from 'react-markdown'
import {render} from 'react-dom'
import directive from 'remark-directive'
import { MyCustomComponent } from './MyCustomComponent'

// 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} 之类的东西,您都应该使用 MyCustomComponent 作为道具渲染 attributes

抱歉,我没有测试过代码,但希望它能传达出事情的要点,如果您需要一个可行的示例,请告诉我,我会尽力设置一个。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。