所以这是唯一的方式来渲染原始html与reactjs?
// http://facebook.github.io/react/docs/tutorial.html
// tutorial7.js
var converter = new Showdown.converter();
var Comment = React.createClass({
render: function() {
var rawMarkup = converter.makeHtml(this.props.children.toString());
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={{__html: rawMarkup}} />
</div>
);
}
});
我知道有一些很酷的方法可以用JSX标记东西,但我主要感兴趣的是能够呈现原始html(包括所有的类、内联样式等)。像这样复杂的事情:
<!-- http://getbootstrap.com/components/#dropdowns-example -->
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
我不想在JSX中重写所有这些内容。
也许我想错了。请纠正我。
现在有更安全的方法来呈现HTML。我在之前的回答中提到过这个问题。你有4个选项,最后使用dangerlysetinnerhtml。
渲染HTML的方法
Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.
<div>{'First · Second'}</div>
Safer - Use the Unicode number for the entity inside a Javascript string.
<div>{'First \u00b7 Second'}</div>
or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
Or a mixed array with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
Last Resort - Insert raw HTML using dangerouslySetInnerHTML.
<div dangerouslySetInnerHTML={{__html: 'First · Second'}} />
这里有一个解决方案,可以归结为两个步骤:
使用内置api将原始HTML字符串解析为HTML元素
递归地将Element对象(及其子对象)转换为ReactElement对象。
注:这是一个学习的好例子。但是考虑一下其他答案中描述的选项,比如html-to-react库。
本方案特点:
它不使用dangerlysetinnerhtml
它使用React.createElement
可运行的示例存储库。
下面是.jsx代码:
// RawHtmlToReactExample.jsx
import React from "react";
/**
* Turn a raw string representing HTML code into an HTML 'Element' object.
*
* This uses the technique described by this StackOverflow answer: https://stackoverflow.com/a/35385518
* Note: this only supports HTML that describes a single top-level element. See the linked post for more options.
*
* @param {String} rawHtml A raw string representing HTML code
* @return {Element} an HTML element
*/
function htmlStringToElement(rawHtml) {
const template = document.createElement('template');
rawHtml = rawHtml.trim();
template.innerHTML = rawHtml;
return template.content.firstChild;
}
/**
* Turn an HTML element into a React element.
*
* This uses a recursive algorithm. For illustrative purposes it logs to the console.
*
* @param {Element} el
* @return {ReactElement} (or a string in the case of text nodes?)
*/
function elementToReact(el) {
const tagName = el.tagName?.toLowerCase(); // Note: 'React.createElement' prefers lowercase tag names for HTML elements.
const descriptor = tagName ?? el.nodeName;
const childNodes = Array.from(el.childNodes);
if (childNodes.length > 0) {
console.log(`This element ('${descriptor}') has child nodes. Let's transform them now.`);
const childReactElements = childNodes.map(childNode => elementToReact(childNode)).filter(el => {
// In the edge case that we found an unsupported node type, we'll just filter it out.
return el !== null
});
return React.createElement(tagName, null, ...childReactElements);
} else {
// This is a "bottom out" point. The recursion stops here. The element is either a text node, a comment node,
// and maybe some other types. I'm not totally sure. Reference the docs to understand the different node
// types: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
console.log(`This element ('${descriptor}') has no child nodes.`);
// For simplicity, let's only support text nodes.
const nodeType = el.nodeType;
if (nodeType === Node.TEXT_NODE) {
return el.textContent;
} else {
console.warn(`Unsupported node type: ${nodeType}. Consider improving this function to support this type`);
return null;
}
}
}
export function RawHtmlToReactExample() {
const myRawHtml = `<p>This is <em>raw</em> HTML with some nested tags. Let's incorporate it into a React element.`;
const myElement = htmlStringToElement(myRawHtml);
const myReactElement = elementToReact(myElement);
return (<>
<h1>Incorporate Raw HTML into React</h1>
{/* Technique #1: Use React's 'dangerouslySetInnerHTML' attribute */}
<div dangerouslySetInnerHTML={{__html: myRawHtml}}></div>
{/* Technique #2: Use a recursive algorithm to turn an HTML element into a React element */}
{myReactElement}
</>)
}
使用类似DOMPurify的东西来净化原始html,然后使用dangerlysetinnerhtml会更安全
我喜欢净化
的类型
NPM I—save-dev @types/dompurify
import React from React
import * as DOMPurify from DOMPurify;
Let dirty = '<b>hello there</b>';
净化。消毒(脏的);
函数MyComponent() {
return <div dangerlysetinnerhtml ={{__html: clean)}} />;
}
如果在您的特定设置中有问题,可以考虑考虑惊人的isomorphic-dompurify项目,它可以解决人们可能遇到的许多问题。
NPM I同构-dompurify
import React from React
从isomorphic-dompurify导入DOMPurify;
Const dirty = '<p>hello</p>'
const clean = dompurification .sanitize(脏的);
函数MyComponent() {
return <div dangerlysetinnerhtml ={{__html: clean)}} />;
}
为演示
https://cure53.de/purify
更多的
https://github.com/cure53/DOMPurify
https://github.com/kkomelin/isomorphic-dompurify