我如何在 React Native 中解析 HTML 文件?
How do I parse an HTML file in React Native?
如何从文件系统获取 HTML 文件并从中解析特定元素。
例如,给定下面的 html 片段,我如何提取 table 内容并呈现它?
<html>
<div>
<h1>header</h1>
<table id="a" border="1">
<th>Number</th>
<th>content A</th>
<th>contetn A</th>
<th>content A</th>
<tr>
<td>1</td>
<td>a</td>
<td>a</td>
<td>a</td>
</tr>
<th>Number</th>
<th>content B</th>
<th>content B</th>
<th>content B</th>
<tr>
<td>1</td>
<td>b</td>
<td>b</td>
<td>b</td>
</tr>
</table>
</div>
<br>
<footer>footer</footer>
</html>
只需使用 fetch() 下载 HTML,使用 fast-html-parser, write result to state and render that state with WebView
解析它
用fetch()获取html,用[=11=解析],用WebView处理显示。
import DOMParser from 'react-native-html-parser';
fetch('http://www.google.com').then((response) => {
const html = response.text();
const parser = new DOMParser.DOMParser();
const parsed = parser.parseFromString(html, 'text/html');
parsed.getElementsByAttribute('class', 'b');
});
P.S。其他答案中的 fast-html-parser 对我不起作用。使用 react-native 0.54.
安装时出现多个错误
我推荐使用这个库:react-native-htmlviewer。它需要 html 并将其呈现为本机视图。您还可以自定义元素的呈现方式。
// only render the <table> nodes in your html
function renderNode(node, index, siblings, parent, defaultRenderer) {
if (node.name !== 'table'){
return (
<View key={index}>
{defaultRenderer(node.children, parent)}
</View>
)l
}
}
// your html
const htmlContent = `<html></html>`;
class App extends React.Component {
render() {
return (
<HTMLView value={htmlContent} renderNode={renderNode} />
);
}
}
我推荐这个包react-native-render-html,非常有名而且使用起来非常简单
如何从文件系统获取 HTML 文件并从中解析特定元素。
例如,给定下面的 html 片段,我如何提取 table 内容并呈现它?
<html>
<div>
<h1>header</h1>
<table id="a" border="1">
<th>Number</th>
<th>content A</th>
<th>contetn A</th>
<th>content A</th>
<tr>
<td>1</td>
<td>a</td>
<td>a</td>
<td>a</td>
</tr>
<th>Number</th>
<th>content B</th>
<th>content B</th>
<th>content B</th>
<tr>
<td>1</td>
<td>b</td>
<td>b</td>
<td>b</td>
</tr>
</table>
</div>
<br>
<footer>footer</footer>
</html>
只需使用 fetch() 下载 HTML,使用 fast-html-parser, write result to state and render that state with WebView
解析它用fetch()获取html,用[=11=解析],用WebView处理显示。
import DOMParser from 'react-native-html-parser';
fetch('http://www.google.com').then((response) => {
const html = response.text();
const parser = new DOMParser.DOMParser();
const parsed = parser.parseFromString(html, 'text/html');
parsed.getElementsByAttribute('class', 'b');
});
P.S。其他答案中的 fast-html-parser 对我不起作用。使用 react-native 0.54.
安装时出现多个错误我推荐使用这个库:react-native-htmlviewer。它需要 html 并将其呈现为本机视图。您还可以自定义元素的呈现方式。
// only render the <table> nodes in your html
function renderNode(node, index, siblings, parent, defaultRenderer) {
if (node.name !== 'table'){
return (
<View key={index}>
{defaultRenderer(node.children, parent)}
</View>
)l
}
}
// your html
const htmlContent = `<html></html>`;
class App extends React.Component {
render() {
return (
<HTMLView value={htmlContent} renderNode={renderNode} />
);
}
}
我推荐这个包react-native-render-html,非常有名而且使用起来非常简单