You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React-Native中使用Google Chart?图表无法渲染问题求助

问题诊断

你当前的写法存在核心逻辑错误:

  • react-google-charts是面向Web端React项目的组件库,其导出的<Chart>是JSX组件,不能直接作为纯字符串塞入WebView的HTML模板中
  • WebView加载的是独立的纯HTML运行环境,没有内置React框架,也无法识别JSX语法,因此你传入的内容只会被当成无效的自定义标签处理,不会渲染出图表
解决方案

直接在WebView的HTML模板中使用Google Charts原生JS API绘制图表,修复后的完整代码如下:

import React from 'react';
import {StyleSheet, View} from 'react-native';
import {WebView} from 'react-native-webview';

const ChartScreen = (props: any) => {
    // 完整可运行的Google Charts HTML模板
    const ExampleChart = `
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      const data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work', 11],
        ['Eat', 2],
        ['Commute', 2],
        ['Watch TV', 2],
        ['Sleep', 7]
      ]);

      const options = {
        title: 'My Daily Activities',
        width: '100%',
        height: 300
      };

      const chart = new google.visualization.PieChart(document.getElementById('piechart'));
      chart.draw(data, options);
    }
  </script>
</head>
<body style="margin:0;padding:0">
  <div id="piechart"></div>
</body>
</html>`;

    return (
        <View style={styles.container}>
            <WebView 
                source={{html: ExampleChart}} 
                style={styles.webStyle}
                javaScriptEnabled={true}
                domStorageEnabled={true}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    webStyle: {
        marginTop: 20,
        height: 500,
        width: '100%',
    },
});

export default ChartScreen;
额外注意事项
  • 确保应用已开启网络权限,HTML模板需要加载Google Charts的在线资源
  • 如果需要动态修改图表数据,可通过WebView的injectedJavaScript属性将动态数据注入到HTML页面中,无需硬编码在模板内
  • WebView默认已开启JS支持,如遇异常可检查是否手动关闭了javaScriptEnabled配置

内容的提问来源于stack exchange,提问作者pratteek shaurya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 12:54:03