问题描述
我想在 reactjs 中使用标记,如 reactjs 文档中所述.
{marked(mystring)}
我使用 babel,所以我像这样导入:
import {marked } from 'marked';
不幸的是,import 语句不起作用.标记未定义.我如何在此处导入标记,以便我可以使用它?
这是一种将 marked
与 React
结合使用的方法:
- 确保您已安装
marked
- 在项目的
package.json
文件中包含marked
:
"dependencies": {反应":^0.13.3",标记":^0.3.5"},
- 在您的
.jsx
(或相关的) 文件中导入marked
:
import 标记自 'marked';
- 使用 中描述的
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
:
- Ensure that you've installed
marked
- Include
marked
in your project'spackage.json
file:
"dependencies": {
"react": "^0.13.3",
"marked": "^0.3.5"
},
- Import
marked
in your.jsx
(or related) file:
import marked from 'marked';
- Use the
dangerouslySetInnerHTML
approach described in thetutorial7.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.
这篇关于在反应中使用标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!