在react native中生成随机QR



我已经通过要求用户输入值手动生成了二维码,但我尝试的是在不要求用户输入的情况下随机生成二维码(QR应该根据数字生成(,所以我如何仅通过按下按钮生成随机二维码?我正在做一个项目,每次他们打开手机应用程序时都需要随机二维码。

这是我的代码:

import React, { Component } from "react";
import {
StyleSheet,
View,
TextInput,
TouchableOpacity,
Text,
} from "react-native";
import QRCode from "react-native-qrcode-svg";
class QrGenerator extends Component {

constructor() {
super();
this.state = {
// Default Value of the TextInput
inputValue: "",
// Default value for the QR Code
valueForQRCode: "",
};
}
getTextInputValue = () => {
this.setState({
valueForQRCode: this.state.inputValue,
});
};
render() {
return (
<View style={styles.MainContainer}>
<QRCode
//Setting the value of QRCode
value={"ComputerGen" + this.state.valueForQRCode}
//Size of QRCode
size={250}
//Background Color of QRCode
bgColor="#000"
//Front Color of QRCode
fgColor="#fff"
getRef={(ref) => (this.svg = ref)}
onPress={() => {}}
/>
<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"
/>
<TouchableOpacity
onPress={this.getTextInputValue}
activeOpacity={0.7}
style={styles.button}
>
<Text style={styles.TextStyle}> Generate QR Code </Text>
</TouchableOpacity>
</View>
);
}
}
export default QrGenerator;
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,
},
});

您想要做的是生成一个随机字符串"inputValue";如果它是空的。

getTextInputValue = () => {
if (this.state.inputValue.length === 0) {
const randomInputValue = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
this.setState({
valueForQRCode: randomInputValue,
inputValue: randomInputValue,
});
} else {
this.setState({
valueForQRCode: this.state.inputValue,
});
}
};

相关内容

  • 没有找到相关文章

最新更新