React:替换文本中的链接

React: replace links in a text

用 React 替换字符串中的 url 并将它们呈现为链接的正确方法是什么?

假设我有一个字符串:'hello http://google.com world',我希望它呈现为:hello <a href="http://google.com">http://google.com</a> world

好的,我就是这样做的。

class A extends React.Component {
  renderText() {
    let parts = this.props.text.split(re) // re is a matching regular expression
    for (let i = 1; i < parts.length; i += 2) {
      parts[i] = <a key={'link' + i} href={parts[i]}>{parts[i]}</a>
    }
    return parts
  }
  render() {
    let text = this.renderText()
    return (
      <div className="some_text_class">{text}</div>
    )
  }
}

试试这个库,它正是你需要的: https://www.npmjs.com/package/react-process-string

那里的一个例子:

const processString = require('react-process-string');

let config = [{
    regex: /(http|https):\/\/(\S+)\.([a-z]{2,}?)(.*?)( |\,|$|\.)/gim,
    fn: (key, result) => <span key={key}>
                             <a target="_blank" href={`${result[1]}://${result[2]}.${result[3]}${result[4]}`}>{result[2]}.{result[3]}{result[4]}</a>{result[5]}
                         </span>
}, {
    regex: /(\S+)\.([a-z]{2,}?)(.*?)( |\,|$|\.)/gim,
    fn: (key, result) => <span key={key}>
                             <a target="_blank" href={`http://${result[1]}.${result[2]}${result[3]}`}>{result[1]}.{result[2]}{result[3]}</a>{result[4]}
                         </span>
}];

let stringWithLinks = "Watch this on youtube.com";
let processed = processString(config)(stringWithLinks);

return (
    <div>Hello world! {processed}</div>
);

这将替换所有带有或不带有 "http://" 协议的链接。如果只想用协议替换链接,请从配置数组中删除第二个对象。

根据 OP 自己的回答,我得出了一个结论:

{text
  .split(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi)
  .map((part, index) => index % 2 === 0 ? part : <a href={part} target="_blank">{part}</a>
}

首先将 <a> 标记添加到字符串:

function httpHtml(content) {
  const reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
  return content.replace(reg, "<a href=''></a>");
}

console.log(httpHtml('hello http://google.com world'))
// => hello <a href="http://google.com">http://google.com</a> world

然后在反应中将字符串呈现为 html:

function MyComponent() {
  return <div dangerouslySetInnerHTML={{
    __html: httpHtml('hello http://google.com world')
  }} />;
}

有 NPM 模块可以处理这个问题。这两个都依赖于 linkify-it (repo)

react-linkify (repo)

<Linkify>
  <div>react-linkify <span>(tasti.github.io/react-linkify/)</span></div>
    <div>React component to parse links (urls, emails, etc.) in text into clickable links</div>
  See examples at tasti.github.io/react-linkify/.
    <footer>Contact: tasti@zakarie.com</footer>
</Linkify>

撰写本文时,当前版本为 1.0.0-alpha。它需要 React 16。repo 有 14 个公开票和 17 个公开 PR。所以这并不好。

版本 0.2.2 允许更早的版本,但没有 link 文本修饰等

react-native-hyperlink ( repo)

如果您使用的是本机(即 phone 应用程序),这看起来是两个选项中更好的一个。代码示例:

<Hyperlink linkDefault={ true }>
  <Text style={ { fontSize: 15 } }>
    This text will be parsed to check for clickable strings like https://github.com/obipawan/hyperlink and made clickable.
  </Text>
</Hyperlink>

<Hyperlink onLongPress={ (url, text) => alert(url + ", " + text) }>
  <Text style={ { fontSize: 15 } }>
    This text will be parsed to check for clickable strings like https://github.com/obipawan/hyperlink and made clickable for long click.
  </Text>
</Hyperlink>

<Hyperlink
  linkDefault
  injectViewProps={ url => ({
        testID: url === 'http://link.com' ? 'id1' : 'id2' ,
        style: url === 'https://link.com' ? { color: 'red' } : { color: 'blue' },
        //any other props you wish to pass to the component
  }) }
>
  <Text>You can pass props to clickable components matched by url.
    <Text>This url looks red https://link.com
  </Text> and this url looks blue https://link2.com </Text>
</Hyperlink>

参考资料

我 运行 对这里的每个答案都有疑问,所以我不得不自己写:

// use whatever you want here
const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;

const renderText = txt =>
  txt
    .split(" ")
    .map(part =>
      URL_REGEX.test(part) ? <a href={part}>{part} </a> : part + " "
    );

我写了一个简短的函数来做到这一点:

const RE_URL = /\w+:\/\/\S+/g;

function linkify(str) {
  let match;
  const results = [];
  let lastIndex = 0;
  while (match = RE_URL.exec(str)) {
    const link = match[0];
    if (lastIndex !== match.index) {
      const text = str.substring(lastIndex, match.index);
      results.push(
        <span key={results.length}>{text}</span>,
      );
    }
    results.push(
      <a key={results.length} href={link} target="_blank">{link}</a>
    );
    lastIndex = match.index + link.length;
  }
  if (results.length === 0) {
    return str;
  }
  if (lastIndex !== str.length) {
    results.push(
      <span key={results.length}>{str.substring(lastIndex)}</span>,
    );
  }
  return results;
}

聚会迟到了,但这里有一个稍微修改过的版本:

export const linkRenderer = (string: string):ReactNode => {
    const linkExp = /^https?:\/\/[a-z0-9_./-]*$/i
    return <>{
        string.split(/(https?:\/\/[a-z0-9_./-]*)/gi).map((part, k) => <React.Fragment key={k}>
            {part.match(linkExp) ? <a
                href={part}
                onFocus={(e) => { e.stopPropagation() }}
                target="_blank"
                rel="noreferrer"
            >{part}</a>
            : part}
        </React.Fragment>)
    }</>
}

这里需要注意的有趣事项:

  • 它不会在 space 或空白 space 上拆分,因此保留现有的 spaces
  • 它通过仅拆分 link 不是每个单词左右的部分来创建更少的块
  • 如果您想将 link 作为结果数组的一部分,则传递给 split 的正则表达式必须带有捕获括号。
  • 出于安全原因,在旧版浏览器上,目标空白需要 noreferrer 属性

希望对您有所帮助。