简体   繁体   English

在反应中将纯字符串转换为 html

[英]Convert plain string to html in react

**How can I convert this plain text to HTML in reactjs? **如何在 reactjs 中将此纯文本转换为 HTML?

**Text:** 

The standard Lorem Ipsum passage, used since the 1500s

Lorem ipsum dolor sit amet, consectetur adipiscing elit

It automatically converts like this:它会自动转换如下:

<p>The standard Lorem Ipsum passage, used since the 1500s</p>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>

I'm not sure what you are trying to do, but you can split the string line by line, here's an example:我不确定您要做什么,但是您可以逐行拆分字符串,这是一个示例:

<div>
  {`The standard Lorem Ipsum passage, used since the 1500s
    
    Lorem ipsum dolor sit amet, consectetur adipiscing elit`
    .split("\n")
    .map((line) => (
      <p style={{ backgroundColor: "#D8DC6A" }}>{line}</p>
    ))}
</div>

You can see the results in this code sandbox您可以在此代码沙箱中看到结果

You can store the needed strings in a state or simple variables or even can pass from props.您可以将所需的字符串存储在 state 或简单变量中,甚至可以从道具传递。

Then on rendering, you can map them as html elements.然后在渲染时,您可以将 map 它们作为 html 元素。

code代码

const DemoComponent = props => {
  const strings = ['The standard Lorem Ipsum passage, used since the 1500s',
                   'Lorem ipsum dolor sit amet, consectetur adipiscing elit]
  return (
  <div>
    {strings.map( element => <p> {element}</p>)}
  </div>);

}

export default DemoComponent;

Note - i have not run this code, but the logic would be same注意- 我没有运行这段代码,但逻辑是一样的

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

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