【问题标题】:Placing html tag inside string将html标签放在字符串中
【发布时间】:2019-02-05 12:53:22
【问题描述】:

这似乎很容易,但由于某种原因我做不到。

在 React 中我有一个对象:

const test = {
  paragraphs: [
    'text of paragraph A text <a>link</a> text', //<a> tag will be printed just as a string
    'text of paragraph B text text',
  ]
}

我正在映射段落以便渲染几个段落,就像这样。

test.paragraphs.map(item => <p>item</p>)

一切正常。但是如果我想在第一段中放置一个链接标签怎么办。如何在数组的第一个字符串中嵌入 html 标签?

【问题讨论】:

  • 你键盘上的&lt; 键是坏了还是什么? (您应该提供minimal reproducible example 和明确的问题陈述)
  • 你的链接有特定的格式吗?
  • @kemicofa 不,这是典型的
  • 分享代码。你是如何渲染这些段落的?我在这些段落中没有看到任何 html 代码
  • 我更新了我的问题,伙计们

标签: javascript reactjs


【解决方案1】:

这是一个如何在 reactjs 应用程序中将字符串转换为 HTML 的示例

class App extends React.Component {

constructor() {
    super();
    this.state = {
      description: '<a href={to} target="_blank" {...rest}>{children}</a>'
    }
  }

  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.state.description }} />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

【讨论】:

    【解决方案2】:

    React 不会自动将你的字符串转换为 JSX 元素,它是渲染器。

    因此,React 允许您将 html 代码注入带有危险的 SetInnerHTML 道具的 HTML 组件中。风险自负:)

    请参阅文档here

    render() {
        return (
            <div dangerouslySetInnerHTML={{ __html: '<p>This is dangerous</p>' }} />
        );
    }
    

    【讨论】:

      【解决方案3】:

      使用String#replace。一个基本的正则表达式,用于查找 url,然后使用回调将链接包装在 &lt;a&gt;

      const test = {
        paragraphs: [
          'text of paragraph A text http://google.com',
          'text of paragraph B text text',
          'text of paragraph http://www.yahoo.com B text text',
          'text http://google.com of paragraph http://www.yahoo.com B text text',
        ]
      };
      
      const res = test.paragraphs.map(p=>{
         return `<p>${p.replace(/http(s)?\:\/\/(www.)?[a-zA-Z]+\.[a-z]+/g, (link)=>`<a href="${link}">${link}</a>`)}</p>`;
         
      });
      
      document.body.innerHTML = res.join("");

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-14
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        相关资源
        最近更新 更多