简体   繁体   English

使用React将HTML元素插入DOM

[英]Insert HTML element into DOM with React

I'm using Regex to bold characters using a double underscore. 我使用正则表达式使用双下划线将字符加粗。 This is my regex, which works: 这是我的正则表达式,它的工作原理是:

"I'm making __this__ bold".replace(/\__([^*]+)\__/g,"<b>$1</b>");

Which gives me this: 这给了我这个:

"I'm making <b>this</b> bold" 

But how do I get it work with React? 但是我如何使其与React一起使用呢? I have the following code, which doesn't work: 我有以下代码,该代码不起作用:

 {cars.map(car => {
   return (
    <div>
     <p>{car.description.replace(/\__([^*]+)\__/g,"<b>$1</b>")}</p>
    </div>         
  )})}

In this case {car.description} would be for example: 在这种情况下,{car.description}例如:

   "The __Audi RS 6 quattro__, commonly referred to as __the RS6__"

And I would like it to show up as: 我希望它显示为:

"The Audi RS 6 quattro , commonly referred to as the RS6 " 奥迪RS 6 quattro ,通常称为RS6

EDIT: 编辑:

With this 有了这个

  <p>{car.description.replace(/\__([^*]+)\__/g,"<b>$1</b>")}</p>

I get back a string: 我得到一个字符串:

   "The <b>Audi RS 6 quattro</b>, ..."

But how do I make JSX recognise to show it as bold, and not with the 但是如何使JSX识别为粗体显示,而不是
tags on the frontend? 前端标签?

What you need is dangerouslySetInnerHTML 您需要的是危险的SetInnerHTML

{cars.map(car => {
   var description = car.description.replace(/\__([^*]+)\__/g,"<b>$1</b>");
   return (
    <div>
     <p dangerouslySetInnerHTML={{__html: description}}/>
    </div>         
  )})}

Sample snippet 样本片段

 const App = () => { var car = "I'm making __this__ bold"; var newCar = car.replace(/\\__([^*]+)\\__/g,"<b>$1</b>"); return ( <div dangerouslySetInnerHTML={{__html: newCar}} /> ) } ReactDOM.render(<App/>, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="app"></div> 

I advise against using dangerouslySetInnerHTML , which — as implied by its name — is dangerous (the output won't be what you expect if car.description contains characters such as & or < ). 我建议不要使用dangerouslySetInnerHTML car.description ,这很危险(顾名思义,这很危险)(如果car.description包含&<字符),输出将不会是您期望的。

You can produce your own elements instead: 您可以改为生成自己的元素:

return (
  <p>{car.description.split('__').map((v, i) => i % 2 ? <b key={i}>{v}</b> : v)}</p>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM