【问题标题】:How to use google chart in React-Native?如何在 React-Native 中使用谷歌图表?
【发布时间】:2021-09-29 20:17:28
【问题描述】:

我正在尝试在我的 react native 应用中使用谷歌图表。

下面是我的代码:

import React, {useState, useEffect} from 'react';
import {StyleSheet, View} from 'react-native';
import {WebView} from 'react-native-webview';
import {Chart} from 'react-google-charts';

const ChartScreen = (props: any) => {
    const ExampleChart = `
            <div className={'my-pretty-chart-container'}>
                <Chart
                    width={'500px'}
                    height={'300px'}
                    chartType="PieChart"
                    loader={<div>Loading Chart</div>}
                    data={[
                    ['Task', 'Hours per Day'],
                    ['Work', 11],
                    ['Eat', 2],
                    ['Commute', 2],
                    ['Watch TV', 2],
                    ['Sleep', 7],
                    ]}
                    options={{
                    title: 'My Daily Activities',
                    }}
                    rootProps={{ 'data-testid': '1' }}
                />
            </div>`;

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

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

export default ChartScreen;

我正在使用 react-native-webview 显示来自 react-google-charts 的图表。

但是图表没有出现在屏幕上,我不知道我做错了什么..!!

【问题讨论】:

    标签: reactjs react-native react-native-android react-native-ios react-google-charts


    【解决方案1】:

    您不能直接将 JSX 作为字符串传递给 WebView。您需要先渲染 ReactJS 元素,然后再将其传递给 WebView,如下所示:

    import { renderToString } from 'react-dom/server'
    import { WebView } from 'react-native-webview';
    import ExampleChart from './path-to-component';
    
    <WebView source={{ html: renderToString(<ExampleChart />) }}></WebView>;
    

    我没有测试它,但理论上它应该可以工作。

    关于ReactDOMServer的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 2018-12-17
      • 2020-07-22
      • 2022-01-08
      • 1970-01-01
      相关资源
      最近更新 更多