使文本URL在div中可点击 [英] Making text urls clickable in a div

查看:32
本文介绍了使文本URL在div中可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使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>

这篇关于使文本URL在div中可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆