繁体   English   中英

如何在 React Native 中解析 HTML 文件?

[英]How do I parse an HTML file in React Native?

如何从文件系统获取 HTML 文件并从中解析特定元素。

例如,给定下面的 html 片段,我如何提取表格内容并呈现它?

 <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对其进行解析,将结果写入状态并使用WebView呈现该状态

使用 fetch() 获取 html 并使用react-native-html-parser 解析,使用 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');
});

其他答案中的 PS 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 ,非常有名并且使用起来非常简单

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM