我在后端使用标准的html RTF编辑器,它与所有标签和其他人员一起存储在MongoDB中。这是一个具有CRUD功能的简单MERN项目。 HTML存储在“内容”字段中。 但是,当我将其通过props传递到我的React组件时,在浏览器中,我看到的是带有所有标签的html,而不是“正确的”文本。 如何在React中正确执行?
Post组件看起来像:
import React, { Component } from "react";
class Post extends Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<h3>{this.props.longTitle}</h3>
{this.props.content}
</div>
);
}
}
export default Post;
此处发布的帖子:
import React, { Component } from "react";
import Post from "./Post";
import { BrowserRouter, Switch, Route, Link } from "react-router-dom";
import axios from 'axios';
import AddService from "./AddService";
class Services extends Component {
constructor(props) {
super(props);
this.state = {
services: [],
loading: true,
error: false,
};
}
componentDidMount() {
console.log("services");
axios.get('http://localhost:5555/services')
.then(res => {
const services = res.data;
this.setState({ services, loading: false });
})
.catch(err => { // log request error and prevent access to undefined state
this.setState({ loading: false, error: true });
console.error(err);
})
}
render() {
if (this.state.loading) {
return (
<div>
<p> Loading... </p>
</div>
)
}
if (this.state.error || !this.state.services) {
return (
<div>
<p> An error occured </p>
</div>
)
}
return (
<div>
<div className="center">
<h2 className="underline">Добавить сервис</h2>
<img src={require("../img/orn.png")} alt="" className="orn" />
</div>
<AddService />
<BrowserRouter>
<Link to="/services">
<h2 className="center">Сервисы</h2>
</Link>
<br />
<div className="center">
<img src={require("../img/orn.png")} alt="" className="orn" />
</div>
<Switch>
<Route
exact
path="/services"
render={() => <Home services={this.state.services} />}
/>
<Route
path="/services/:_id"
render={props => {
const _id = props.match.params._id;
const data = this.state.services.find(item => item._id == _id);
if (data) {
return <Post {...props} {...data} />;
}
}}
/>
</Switch>
</BrowserRouter>
</div>
);
}
}
class Home extends Component {
render() {
return (
<div>
{this.props.services.map(post => (
<h3>
<Link to={`/services/${post._id}`}>{post.title}</Link>
</h3>
))}
</div>
);
}
}
export default Services;
正确的方法是什么? 谢谢大家!)
答案 0 :(得分:0)
您可以使用react-render-html
软件包。
首先将其安装到您的依赖项:npm install react-render-html
然后:您的Post
中的组件,假设this.props.content
是一个包含您要呈现的HTML的字符串:
import React, { Component } from "react";
import renderHTML from 'react-render-html';
class Post extends Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<h3>{this.props.longTitle}</h3>
{renderHTML(this.props.content)}
</div>
);
}
}
export default Post;