Как передать данные API из собственного кода реакции в html и наоборот в реакции-нативного- html -to-pdf - PullRequest
0 голосов
/ 04 мая 2020

Я использую act-native- html -to-pdf пакет для создания pdf-файла. Я хочу передать ответ API от Reaction-native в html и получить данные от html. параметры, доступные для этого npm пакета, минимальны

В пакете нет параметров, чтобы я мог его использовать, может кто-нибудь мне помочь с этим? Ниже мой код.

import React, { Component } from 'react';
import { Text, TouchableOpacity, View, StyleSheet, Image, PermissionsAndroid, Platform,} from 'react-native';
import RNHTMLtoPDF from 'react-native-html-to-pdf';
import htmlContent from './htmlContent'

export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
        apiData: [],
        filePath: ''
    }
  }

  askPermission() {
    var that = this;
    async function requestExternalWritePermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'External Storage Write Permission',
            message:
              'App needs access to Storage data in your SD Card ',
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          that.createPDF();
        } else {
          alert('WRITE_EXTERNAL_STORAGE permission denied');
        }
      } catch (err) {
        alert('Write permission err', err);
        console.warn(err);
      }
    }
    if (Platform.OS === 'android') {
      requestExternalWritePermission();
    } else {
      this.createPDF();
    }
  }

    componentDidMount(){
        fetch(`http://API`)
            .then((response) => response.json())
            .then((responseJson) => {
                **console.log("DATA", responseJson) // NEED TO SEND THIS DATA TO "HTML"**
                this.setState(() => ({
                    apiData: responseJson
                }))
        })
    }

  async createPDF() {
    let options = {
      html:htmlContent, // API DATA SHOULD BE SENT TO HTML
      fileName: 'RTT Report',
      directory: 'docs',
      width: 800,
    };
    let file = await RNHTMLtoPDF.convert(options);
    console.log(file.filePath);
    this.setState({filePath:file.filePath});
  }

  render() {
    return (
      <View style={styles.MainContainer}>
        <TouchableOpacity onPress={this.askPermission.bind(this)}>
        <View>
          <Image
            //We are showing the Image from online
            source={{
              uri:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/pdf.png',
            }}
            //You can also show the image from you project directory like below
            //source={require('./Images/facebook.png')}
            style={styles.ImageStyle}
          />
          <Text style={styles.text}>Create PDF</Text>
          </View>
        </TouchableOpacity>
        <Text style={styles.text}>{this.state.filePath}</Text>
      </View>
    );
  }
}

1 Ответ

0 голосов
/ 04 мая 2020

В методе createPDF:

// html:htmlContent, // API DATA SHOULD BE SENT TO HTML
html: this.state.apiData // <-- you have stored your html in the state

РЕДАКТИРОВАТЬ: Возможно, я слишком быстро отвечал, теперь я думаю, что я понял вашу точку зрения, вот вам пример:

// html: '<h1>PDF TEST</h1>', <-- example from react-native-html-to-pdf

const exampleData = [
    {
        title: "Element title",
        content: "Element content"
    },
    {
        title: "Other title",
        content: "Other element content"
    }
]

function generateHTML () {
    const data = exampleData
    // const data = this.state.apiData // <-- in your case
    let htmlContent = '<html><body>'
    htmlContent += data.map(entry => {
        return `<h5>${entry.title}</h5> <br /> <p>${entry.content}</p>`
    }).join(' ')
    htmlContent += '</body></html>'
    return htmlContent
}
...