React Native如何检测链接形式字符串并将其转换为链接?

skl*_*est 3 react-native

我希望用户能够从评论(字符串)中获取链接,类似于linkify。有没有简单的方法可以做到这一点?我相信可以在这里解决(https://github.com/facebook/react-native/issues/3148),但是我不太确定如何实现它。谢谢。

vil*_*aka 5

我根据链接中的组件做了一个快速演示

我无法在该环境中测试 LinkingIOS,但这些文档应该可以帮助您实现。

这是原始来源:

var HyperText = React.createClass({

  render: function() {

    // Check if nested content is a plain string
    if (typeof this.props.children === 'string') {

      // Split the content on space characters
      var words = this.props.children.split(/\s/);

      // Loop through the words
      var contents = words.map(function(word, i) {

        // Space if the word isn't the very last in the set, thus not requiring a space after it
        var separator = i < (words.length - 1) ? ' ' : '';

        // The word is a URL, return the URL wrapped in a custom <Link> component
        if (word.match(/^https?\:\//)) {
          return <Link key={i} url={word}>{word}{separator}</Link>;
        // The word is not a URL, return the word as-is
        } else {
          return word + separator;
        }
      });
    // The nested content was something else than a plain string
    // Return the original content wrapped in a <Text> component
    } else {
      console.log('Attempted to use <HyperText> with nested components. ' +
                   'This component only supports plain text children.');
      return <Text>{this.props.children}</Text>;
    }

    // Return the modified content wrapped in a <Text> component
    return (
      <Text>
        {contents}
      </Text>
    );
  }

});

var Link = React.createClass({

  render: function() {
    return <Text onPress={this.openUrl.bind(this, this.props.url)}>{this.props.children}</Text>;
  },

  openUrl: function(url) {
    LinkingIOS.canOpenURL(url, (supported) => {
      if (!supported) {
        AlertIOS.alert('Can\'t handle url: ' + url);
      } else {
        LinkingIOS.openURL(url);
      }
    });
  }

});
Run Code Online (Sandbox Code Playgroud)

希望这有点帮助。


ant*_*129 5

您可以使用react-native-hyperlink

import Hyperlink from 'react-native-hyperlink'
import {Text, Linking} from 'react-native'

const MyComponent = () => (
  <Hyperlink onPress={Linking.openURL}>
    <Text>{"Click on https://stackoverflow.com to test"}</Text>
  </Hyperlink>
)
Run Code Online (Sandbox Code Playgroud)


Com*_*02x 5

尝试这个库react-native-autolink,它可以检测它是否是hyperlinkhashtagmentionemailphone number

import Autolink from 'react-native-autolink';

class MyComponent extends Component {
    render() {
      return (
        <Autolink
            text="This is the string to parse for urls (https://github.com/joshswan/react-native-autolink), phone numbers (415-555-5555), emails (josh@example.com), mentions/handles (@twitter), and hashtags (#exciting)"
            hashtag="instagram"
            mention="twitter"
        />
      );
    }
}
Run Code Online (Sandbox Code Playgroud)