将消息中的 link 秒显示为 link

Display links from message as a link

我正在尝试将文本中出现的任何 link 重播为 link,但我只能将 <a href="example.com">example.com</a> 显示为消息中的文本。 (说明一下,如果消息中除了 link 之外还有其他内容,它会显示其他消息内容,但是 link 得到 "linkified(as seen below)")

这是消息组件。

import React from "react";
import moment from "moment";
import { Comment, Image } from "semantic-ui-react";

const isOwnMessage = (message, user) => {
  return message.user.id === user.uid ? "message__self" : "";
};

const isImage = message => {
  return message.hasOwnProperty("image");
};

const timeFromNow = timestamp => moment(timestamp).fromNow();

function linkify(text) {
  var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
      return '<a href="' + url + '">' + url + '</a>';
  });
}

const Message = ({ message, user }) => (
  <Comment>
    <Comment.Avatar src={message.user.avatar} />
    <Comment.Content className={isOwnMessage(message, user)}>
      <Comment.Author as="a">{message.user.name}</Comment.Author>
      <Comment.Metadata>{timeFromNow(message.timestamp)}</Comment.Metadata>
      {isImage(message) ? (
        <Image src={message.image} className="message__image" />
      ) : (
        <div>
<Comment.Text>{linkify(message.content)}</Comment.Text>
        <React.Fragment dangerouslySetInnerHTML={linkify(message.content)}>
        </React.Fragment>
        </div>
      )}
    </Comment.Content>
  </Comment>
);

export default Message;

你最好先用你的正则表达式对待你的 url 变量然后 return 就像一个有效的反应元素:

function linkify(text) {
  const urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  // extract your url by urlRegex something like
  const url = text.match(urlRegex)[0]
  return <a href={url} >{url}</a>
}
  1. dangerouslySetInnerHTML 道具需要一个带有 __html 属性
  2. 的对象
  3. don't use React.Fragment 当使用 dangerouslySetInnerHTML 时。只需使用 div

Working demo

代码段

function linkify(text) {
  var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
  return text.replace(urlRegex, function(url) {
    return '<a href="' + url + '">' + url + "</a>";
  });
}
const text = `I'm trying to replay any occurrence of a link in a text as a link, but I only get it to show the <a href="example.com">example.com</a> as text in the message. (Just to be clear, it shows other message content if there is other content in the message than the link, but the link gets "linkified(as seen below)")`;
export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <br />
      <div dangerouslySetInnerHTML={{ __html: linkify(text) }} />; }
    </div>
  );
}