我正在做。
import React from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, Linking } from 'react-native';
/**
* Used to create external link to other websites
*/
class ExternalLink extends React.Component {
_openLink = async () => {
const { href } = this.props;
if (await Linking.canOpenURL(href)) {
await Linking.openURL(href);
}
};
render() {
const { href, children, ...rest } = this.props;
return (
<TouchableOpacity
accessibilityRole="link"
onPress={this._openLink} // eslint-disable-line no-underscore-dangle
href={href}
{...rest}
>
{children}
</TouchableOpacity>
);
}
}
ExternalLink.propTypes = {
/** External URL */
href: PropTypes.string.isRequired,
/** Any node */
children: PropTypes.node.isRequired,
};
export default ExternalLink;
但是,这个在当前标签页中打开,有什么方法可以在新的标签页中打开URL?
我想有两个主要的选择。
你可以只使用web中的window.open()函数。
if(Platform.OS == 'web'){
window.open(url, '_blank');
} else {
Linking... // normal Linking react-native
}
或者你可以从react-native-web中创建一个自定义的Linking (https:/github.comnecolasreact-native-webblobmasterpackagesreact-native-websrcexportsLinkingindex.js。):
CustomLinking.js。
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import invariant from 'fbjs/lib/invariant';
const initialURL = canUseDOM ? window.location.href : '';
const CustomLinking = {
addEventListener() {},
removeEventListener() {},
canOpenURL(): Promise<boolean> {
return Promise.resolve(true);
},
getInitialURL(): Promise<string> {
return Promise.resolve(initialURL);
},
openURL(url: string, target = '_self'): Promise<Object | void> {
try {
open(url, target);
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
_validateURL(url: string) {
invariant(typeof url === 'string', 'Invalid URL: should be a string. Was: ' + url);
invariant(url, 'Invalid URL: cannot be empty');
}
};
const open = (url, target) => {
if (canUseDOM) {
window.open(
url,
target // <- This is what makes it open in a new window.
);
}
};
export default CustomLinking;
用法。
import Linking from "./CustomLinking";
Linking.openURL(href, '_blank');