在反应中使用标记 [英] Using marked in react

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

问题描述

我想在 reactjs 中使用标记,如 reactjs 文档中所述.

{marked(mystring)}

我使用 babel,所以我像这样导入:

import {marked } from 'marked';

不幸的是,import 语句不起作用.标记未定义.我如何在此处导入标记,以便我可以使用它?

解决方案

这是一种将 markedReact 结合使用的方法:

  1. 确保您已安装marked
  2. 在项目的 package.json 文件中包含 marked:

"dependencies": {反应":^0.13.3",标记":^0.3.5"},

  1. 在您的 .jsx (或相关的) 文件中导入 marked:

import 标记自 'marked';

  1. 使用 中描述的 dangerouslySetInnerHTML 方法tutorial7.js React 教程中的示例 (如 Janaka 所述),或如下面的示例所示:

从'react'导入React;从标记"导入标记;class MarkdownExample 扩展 React.Component {getMarkdownText() {var rawMarkup = marker('这是_Markdown_.', {sanitize: true});返回 { __html: rawMarkup };}使成为() {return <div risklySetInnerHTML={this.getMarkdownText()}/>}}

React 教程中所述,使用 dangerouslySetInnerHTML 属性为您提供使用原始 (HTML) 标记的能力.不过,请确保使用此属性时要小心

<小时>

注意:步骤 4 中代码示例中的 React.Component 方法基于 Agnew 的 Hello World"示例以及 Goel 和 Silveira 撰写的这篇 React.Component vs React.createClass 文章中的注释.

I want to use marked in reactjs as described in the reactjs docs.

<div>{marked(mystring)}</div>

I use babel so I import marked like this:

import { marked } from 'marked';

Unfortunately the import statement does not work. marked is not defined. How do I have to import marked here, so that I can use it?

解决方案

Here's one way to use marked with React:

  1. Ensure that you've installed marked
  2. Include marked in your project's package.json file:

"dependencies": {
  "react": "^0.13.3",
  "marked": "^0.3.5"
},

  1. Import marked in your .jsx (or related) file:

import marked from 'marked';

  1. Use the dangerouslySetInnerHTML approach described in the tutorial7.js example in the React Tutorial (as noted by Janaka), or as shown in the example below:

import React from 'react';
import marked from 'marked';

class MarkdownExample extends React.Component {
  getMarkdownText() {
    var rawMarkup = marked('This is _Markdown_.', {sanitize: true});
    return { __html: rawMarkup };
  }
  render() {
    return <div dangerouslySetInnerHTML={this.getMarkdownText()} />
  }
}

As discussed in the React Tutorial, using the dangerouslySetInnerHTML attribute gives you the ability to work with raw (HTML) markup. Make sure to take care when using this attribute, though!


Note: the React.Component approach in the code example in Step 4 is based on Agnew's "Hello World" example and on notes from this React.Component vs React.createClass article by Goel and Silveira.

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

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