在React Native Text组件中将锚点标记渲染为超链接



我使用exporeact-native来显示API中的数据。

API正在返回带有<p><a>标记的HTML。我使用react-native的Text组件来显示数据,但它显示的是<a>标记。我想显示通过该锚点标记创建的超链接。

我已经应用了renderHTML包,但使用它,其他标签,如<br/><p>标签会被忽略,文本看起来非常混乱。

使用react原生webview在webview中呈现HTML内容即使在expo管理的工作流中也可以使用此包https://www.npmjs.com/package/react-native-webview

以下是在react原生应用程序中正确呈现HTML的解决方案
安装react原生render html。

npm i react native render html

创建一个名为";HtmlViewer.js":
HtmlViewer.js

import React from 'react';
import HTML from 'react-native-render-html';
import { View, Dimensions, StyleSheet, Text } from 'react-native';
const width = Dimensions.get('window').width;
const HtmlViewer = ({ text, style }) => {
// first check that html is empty or not, otherwise something it display large spacing
if (
!text ||
text === '' ||
text === ' ' ||
text === null ||
text === undefined ||
text === '<p class="ql-align-center"><br></p>' ||
text === '<p class="ql-align-left"><br></p>' ||
text === '<p class="ql-align-right"><br></p>' ||
text === '<p class="ql-align-justify"><br></p>' ||
text === '<p class="ql-align-auto"><br></p>' ||
text === '<p><br></p>'
) {
return null;
}
return (
<View
style={style}>
<HTML
source={{
html: text.replace(/(rn|n|r)/gm, ''), // use replace to remove new line
}}
contentWidth={width}
renderers={{
h1: (htmlAttribs, children, convertedCSSStyles, passProps) => (
<Text
style={htmlViewStyle[htmlAttribs.class]}
key={passProps.key}>
{children}
</Text>
),
h2: (htmlAttribs, children, convertedCSSStyles, passProps) => (
<Text
style={htmlViewStyle[htmlAttribs.class]}
key={passProps.key}>
{children}
</Text>
),
h3: (htmlAttribs, children, convertedCSSStyles, passProps) => (
<Text
style={htmlViewStyle[htmlAttribs.class]}
key={passProps.key}>
{children}
</Text>
),
p: (htmlAttribs, children, convertedCSSStyles, passProps) => (
<Text
style={htmlViewStyle[htmlAttribs.class]}
key={passProps.key}>
{children}
</Text>
),
span: (htmlAttribs, children, convertedCSSStyles, passProps) => (
<Text style={htmlViewStyle[htmlAttribs.class]} key={passProps.key}>
{children}
</Text>
),
}}
allowWhitespaceNodes={false}
classesStyles={htmlViewStyle}
tagsStyles={{
h1: {
fontSize: 38,
},
h2: {
fontSize: 34,
},
h3: {
fontSize: 30,
},
p: {
fontSize: 18,
},
rawtext: {
fontSize: 16,
},
textwrapper: {
fontSize: 16,
},
}}
/>
</View>
);
};
const htmlViewStyle = StyleSheet.create({
'ql-align-center': {
textAlign: 'center',
},
'ql-align-left': {
textAlign: 'left',
},
'ql-align-right': {
textAlign: 'right',
},
'ql-align-justify': {
textAlign: 'justify',
},
});
export default HtmlViewer;

使用此组件来呈现HTML。

import HtmlViewer from '../yourcomponentPath/HtmlViewer.js'
...
...
<HtmlViewer text={yourHtmlText} />

最新更新