0

我正在尝试在我的反应原生应用程序中使用谷歌图表。

下面是我的代码:

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 的图表。

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

4

1 回答 1

0

您不能直接将 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的更多信息。

于 2021-09-29T22:34:41.247 回答