【问题标题】:How do I parse an HTML file in React Native?如何在 React Native 中解析 HTML 文件?
【发布时间】:2016-11-15 14:02:38
【问题描述】:

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

例如,给定下面的html sn-p,如何提取表格内容并渲染?

<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>

【问题讨论】:

    标签: javascript html react-native html-parsing


    【解决方案1】:

    只需使用 fetch() 下载 HTML,使用 fast-html-parser 解析它,将结果写入状态并使用 WebView 呈现该状态

    【讨论】:

    • @Stich 您可以在“fast-html-browser”Github 项目页面上找到示例。
    • 你用什么 react native 版本?我从 43 到 44 尝试过,但模块“fast-html-parser”遇到同样的问题: UnableToResolveError: Unable to resolve module util from /.../node_modules/apollojs/server.js 这些行中你的 package.json 中有哪些版本?:“react” : "^16.0.0-alpha.6", "react-native": "^0.43.4"
    • 不适用于 react native 0.41.2,与@Stich 相同的问题
    • 您好,这是这个问题的答案如果您使用 npm install util 显式安装 util,您可以解决此问题。 github.com/ashi009/node-fast-html-parser/issues/11
    • 它运行良好但你需要运行“npm install util”来解析模块util
    【解决方案2】:

    用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');
    });
    

    附:其他答案中的 fast-html-parser 对我不起作用。使用 react-native 0.54 安装时出现多个错误。

    【讨论】:

    • 项目在 GitHub 上不再有效
    【解决方案3】:

    我会推荐使用这个库: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} />
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多