如何将 axios 响应中的"br"标签替换为实际的"br"标签?



使用:React,WordPress REST API,Axios

我从自定义帖子类型中提取结果,当我得到字段"的结果时;acf.other";它是一个文本框字段,每当用户输入返回时,它要么(取决于cpt设置(放一个<br />标签,要么放</p> <p>标签,要么什么都不放,导致一个不带格式的运行段落。如果它放置了标签,那么结果会在网站上显示标签,而实际上并没有使用标签(请参见img(

export const SingleRecent = () => {
const { singleSlug } = useParams();
const [single,setSingle] = useState([]);
useEffect(() => {
axios.get(recent + singleSlug)
.then(response => {
setSingle(response.data);
})
.catch((error) => {
console.log(error);
})

}, [singleSlug]);

return (
<><div className="pagebg singlePageBg">
<main>
<div className="container notHomeContainer singleContainer">
<div className="gallery notHomeGallery singleGallery">
{single.map(single_recent => <SingleRecentItems key={single_recent.id} single_recent={single_recent} />)}
</div>
</div>
</main>
</div></>
);
}
class SingleRecentItems extends Component {

render() {
let { acf } = this.props.single_recent;
return (
<>
<h1>{acf.title}</h1>
<h4>{acf.style}</h4>
<div className="photos">
<span className="recentPhoto">
<img 
src={acf.photo}
alt={acf.title} 
/>
</span>
</div>
<div className="otherInfo">
{acf.other}
</div>
<div className="location">
Photo Taken in: {acf.location_other}<br />
{acf.location_city}<br />
{acf.location_state}<br />
{acf.location_country}
</div>
<div className="keywords">
{acf.subject}
</div>
</>
)
}
}

我想获得{acf.other}的结果,并将标签转换为功能标签,这样它就可以(或多或少(按照用户想要的方式格式化结果。我可以以某种方式将{acf.other}分配给一个var,解析并连接,然后返回结果吗?有更好的方法吗?

一般规则是,不希望将数据视为代码。如果这是第三方数据,恶意用户可能会在你的网页中写入<script src="steal-their-cookies.xyz">,你更愿意将其视为"<script src=";偷他们的饼干>quot;在页面上,而不是作为执行的代码!将用户生成的数据作为代码插入页面是一种很好的方式,可以让自己暴露在跨站点脚本(XSS(攻击和其他页面破坏和数据窃取的危险中。

然而,在您的情况下,数据被认为是代码,并且被认为是来自可信来源。为了启用您的用例,React有一个dangerouslySetInnerHTML属性,允许您将这些数据视为代码。正如在这个LogRocket博客中一样,这对于一个CMS来说是有道理的,因为它有可信的编辑器提交富文本,但你应该意识到危险,并极其谨慎地使用该属性。

<!-- Beware the caveats above. -->
<div className="otherInfo" dangerouslySetInnerHTML={{__html: acf.other}} />

尝试解析结果String以转义HTML字符。它可能看起来像这样:

parsedResult = response.data
.replace("\u003c", "<")
.replace("\u003d", "=")
.replace("\u003e", ">")
.replace("\u0026", "&");

在这种情况下,您可能需要转义更多的字符。快速查找将为您提供所需的代码。

希望这能有所帮助!

最新更新