使文本URL可以在div中单击

时间:2018-04-18 11:55:05

标签: javascript html reactjs hyperlink href

我正在尝试在我的反应应用程序中使url可单击。我目前的做法如下。

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>

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

您需要从原始文本中提取link text并将其添加到<a>代码中。

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

答案 1 :(得分:1)

默认情况下,React会在字符串中转义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>
  );
}

&#13;
&#13;
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')
);
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

将urlify函数的返回更改为此

return text
          .replace(urlRegex, function(url) {
             return '<a href="' + url + '">' + url +'</a>';
           })