Как сохранить / скачать сгенерировать QRCode inn реагировать на родной - PullRequest
0 голосов
/ 13 февраля 2019

Используя этот код, я могу сгенерировать QRCode, но я не знаю, как сохранить этот qrcode в формате png / jpeg на долгое нажатие или автоматически.Мне нужна помощь или идея, чтобы решить это .. Я попробовал несколько примеров, но не добился успеха.Я продолжаю пытаться.

import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, TextInput, TouchableOpacity, Text,} from 'react-native';
// import all basic components
import QRCode from 'react-native-qrcode-svg';
//import QRCode

class App extends Component {
    svg;
  constructor() {
    super();
    this.state = {
      inputValue: '',
      inputValue2: '',
      // Default Value of the TextInput
      valueForQRCode: '',
      // Default value for the QR Code
    };
  }

  getTextInputValue = () => {
    // Function to get the value from input
    // and Setting the value to the QRCode
    this.setState({ valueForQRCode: this.state.inputValue + this.state.inputValue2 });
  };
  shareQR =()  =>{
    this.svg.toDataURL((data) => {
      const shareImageBase64 = {
        title: "QR",
        message: "Ehi, this is my QR code",
        url: `data:image/png;base64,${data}`
      };
      Share.open(shareImageBase64);
    });
  }
  render() {
    return (
      <View style={styles.MainContainer}>
        <QRCode
          value={"Abhigyan" + this.state.valueForQRCode}
          //Setting the value of QRCode
          size={250}
          //Size of QRCode
          bgColor="#000"
          //Backgroun Color of QRCode
          fgColor="#fff"
          //Front Color of QRCode
          getRef={(ref) => (this.svg = ref)}
          onPress={() =>{shareQR()}}
        />
        <TextInput
          // Input to get the value to set on QRCode
          style={styles.TextInputStyle}
          onChangeText={text => this.setState({ inputValue: text })}
          underlineColorAndroid="transparent"
          placeholder="Enter text to Generate QR Code"
        />

<TextInput
          // Input to get the value to set on QRCode
          style={styles.TextInputStyle}
          onChangeText={text => this.setState({ inputValue2: text })}
          underlineColorAndroid="transparent"
          placeholder="Enter text to Generate QR Code"
        />
        <TouchableOpacity
          onPress={this.getTextInputValue}
          activeOpacity={0.7}
          style={styles.button}>
          <Text style={styles.TextStyle}> Generate QR Code </Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button}onPress={this.shareQR}>
          <Text style={styles.buttonText}>Share</Text>
      </TouchableOpacity>
      </View>
    );
  }
}
export default App;
const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    margin: 10,
    alignItems: 'center',
    paddingTop: 40,
  },

  TextInputStyle: {
    width: '100%',
    height: 40,
    marginTop: 20,
    borderWidth: 1,
    textAlign: 'center',
  },

  button: {
    width: '100%',
    paddingTop: 8,
    marginTop: 10,
    paddingBottom: 8,
    backgroundColor: '#F44336',
    marginBottom: 20,
  },

  TextStyle: {
    color: '#fff',
    textAlign: 'center',
    fontSize: 18,
  },
});

// Спасибо.// В QRCode я могу генерировать и QRCode сканер, как я сделал, но как скачать / сохранить или поделиться этим qrcode, Пожалуйста, помогите

Ответы [ 2 ]

0 голосов
/ 13 февраля 2019

Этот ответ относится к библиотекеact-native-qrcode-svg, как написано в комментариях к вопросу .

С помощью этой библиотеки вы можете создать svg для отображения нужного QR-кода изатем получить доступ к нему по ссылке.Итак, создайте ссылку в вашем компоненте:

class App extends Component {
  svg;
  constructor() {
    ...
    };
  }
...
}

Назначьте ему QRCode, например:

<QRCode
  value={"Abhigyan" +this.state.valueForQRCode}
  size={250}
  color="#fff"
  getRef={(ref?) => (this.svg = ref)}
/>

Теперь вы можете получить доступ к его содержимому с помощью this.svg.toDataURL(//callback).Пример: вы хотите поделиться QR-кодом как изображением / png, используя response-native-share, нажав на кнопку, которая вызывает эту функцию:

  shareQR() {
    this.svg.toDataURL((data) => {
      const shareImageBase64 = {
        title: "QR",
        message: "Ehi, this is my QR code",
        url: `data:image/png;base64,${data}`
      };
      Share.open(shareImageBase64);
    });
  }

Это всего лишь пример, если вы предпочитаете использовать response-native-fs вы можете обратиться к примеру , приведенному в официальном репозитории.

Обновление для поддержки функции onPress

Вы пытаетесь пройтиonPress prop QRCode, но QRCode не поддерживает его.Вместо этого оберните это в TouchableOpacity:

<TouchableOpacity onPress={this.shareQR}>
  <QRCode
    value={"Abhigyan" +this.state.valueForQRCode}
    size={250}
    color="#fff"
    getRef={(ref?) => (this.svg = ref)}
  />
</TouchableOpacity>
0 голосов
/ 13 февраля 2019

Вы можете использовать реагировать-родной-снимок-снимок , чтобы создать изображение QR-кода, затем вы можете сохранить его в видеопленке или на диске.

...