使文本URL在div中可点击

2022-04-03 00:00:00 reactjs href hyperlink javascript html

我正在尝试使URL在我的Reaction应用程序中可点击。我目前的做法如下。

render() {

  function urlify(text) {
    var urlRegex = /(https?://[^s]+)/g;
    return text.replace(urlRegex, function(url) {
      return '<a href="' + url + '">' + '</a>';
    })
  }

  const headingAvailable = (
    <span className="home_post_text">{urlify(postData.heading)}</span>
  );

  return (
    <div className="home_post_sections sec2 unchange_div">{headingAvailable}</div>
  );
}

但我无法使其正常工作。

例如:

如果我的文本是这样的

this is a good song https://www.youtube.com/watch?v=i9wBXC3aZ_I&index=8&list=RDxuAH21DkJow

我的文本转换为类似以下内容

this is a good song <a href="https://www.youtube.com/watch?v=i9wBXC3aZ_I&index=8&list=RDxuAH21DkJow"></a>

如何修复此问题?


解决方案

Reaction默认转义字符串中的html标签,以防止xss安全漏洞。

您需要返回一个a组件,类似于:

render() {

  function urlify(text) {
    const urlRegex = /(https?://[^s]+)/g;
    return text.split(urlRegex)
       .map(part => {
          if(part.match(urlRegex)) {
             return <a href={part}>{part}</a>;
          }
          return part;
       });
  }

  const headingAvailable = (
    <span className="home_post_text">{urlify(postData.heading)}</span>
  );

  return (
    <div className="home_post_sections sec2 unchange_div">{headingAvailable}</div>
  );
}
数据-lang="js"数据-隐藏="真"数据-控制台="真"数据-巴贝尔="真">
class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.text = 'this is a good song https://www.youtube.com/watch?v=i9wBXC3aZ_I&index=8&list=RDxuAH21DkJow';
  }

  urlify(text) {
    const urlRegex = /(https?://[^s]+)/g;
    return text.split(urlRegex)
      .map(part => {
        if (part.match(urlRegex)) {
          return <a href={part} key={part}> {part} </a>;
        }
        return part;
      });
  }

  render() {
    return <div> {this.urlify(this.text)} </div>;
  }
}

ReactDOM.render( <
  Hello name = "World" / > ,
  document.getElementById('container')
);
<script src="https://unpkg.com/react@16.3.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.3.2/umd/react-dom.development.js"></script>
<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>

相关文章