[英]How to render HTML tags in JSX when pulling a string from a database
I'm creating a React.js project and I want to pull a string from Firebase that has HTML tags and render those tags.我正在创建一个 React.js 项目,我想从 Firebase 中提取一个具有 HTML 标签的字符串并渲染这些标签。 However, when I render the string as a string interpolation inside of a JSX element, the HTML tags simply print as text instead of actually taking effect.
但是,当我将字符串呈现为 JSX 元素内的字符串插值时,HTML 标签只是打印为文本而不是实际生效。
Here is the code:这是代码:
import React from 'react';
import styled from 'styled-components';
import { firestore } from '../../firebase/firebase.utils';
const name = firestore.collection('blog-categories').doc('8uVaHd22tT5oXSzpOOuj').get().then(doc =>
doc.get('name'));
class Economics extends React.Component {
constructor() {
super();
this.state = {
name: '',
image: '',
whyRead: ''
}
}
componentDidMount() {
firestore.collection('blog-categories').doc('8uVaHd22tT5oXSzpOOuj').get().then(doc => {
this.setState({ name: doc.get('name'), image: doc.get('image'), whyRead: doc.get('why-read')
});
});
}
render() {
return (
<div>
<h1>{ `${this.state.whyRead}` }</h1>
</div>
)
}
}
export default Economics;
When I run this code, the result is simply the following:当我运行这段代码时,结果如下:
However, I want the HTML bold tags to actually take effect and create bold text.但是,我希望 HTML 粗体标签实际生效并创建粗体文本。 How would I do this?
我该怎么做?
dangerouslySetInnerHTML
危险地设置InnerHTML
dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM.
dangerouslySetInnerHTML 是 React 在浏览器 DOM 中使用 innerHTML 的替代品。 In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack.
通常,从代码中设置 HTML 是有风险的,因为很容易无意中将您的用户暴露给跨站点脚本 (XSS) 攻击。 So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.
因此,您可以直接从 React 设置 HTML,但您必须输入危险的 SetInnerHTML 并使用 __html 键传递 object,以提醒自己这是危险的。
https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
return <div dangerouslySetInnerHTML={{__html: this.state.whyRead}} />;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.