使用Typescript在React中进行Markdown [英] Markdown in React with Typescript

查看:354
本文介绍了使用Typescript在React中进行Markdown的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使用Typescript在React中解析Markdown?

Is there a way to parse Markdown in React using Typescript?

我正在尝试做以下事情:

I am trying to do things like:

import * as ReactMarkdown from 'react-markdown'
// OR
import ReactMarkdown = require('react-markdown')

但是Typescript无法找到未定义的模块'remark-markdown':

But Typescript can't fint module 'react-markdown' as it's not defined:

错误:TS2307:找不到模块'remark-markdown'.

Error: TS2307: Cannot find module 'react-markdown'.

如何定义模块并将其用作React组件?

How can I define the module and use it as a React component?

推荐答案

我通过使用commonmark包解决了我的问题.他们有打字以及我的环境所需的一切.这是我的实现:

I solved my problem by using commonmark package instead. They have typings and everything needed for my environment. Here is my implementation:

import { HtmlRenderer, Parser } from 'commonmark'

export class MyComponent extends React.Component<{}, {}> {
  private post: string

  constructor () {
    super()
    let parser = new Parser()
    let renderer = new HtmlRenderer()
    this.post = renderer.render(parser.parse("**works** like a charm!"))
  }

  render () {
    return (
      <div dangerouslySetInnerHTML={ {__html: this.post} } />
    )
  }
}

此外,不要忘记添加commonmark的类型:

Also, do not forget to add the typings for commonmark:

$ typings install --global --save dt~commonmark

感谢尝试提供帮助的人!

Thanks to the people who tried to help!

这篇关于使用Typescript在React中进行Markdown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆