I am currently following a basic tutorial on React Native authentication. When I launch the project, it gives the following error:
I understand the error, but cannot see what I am doing wrongly. In particular, I commented out my views until the error disappeared and the project compiled. Here is the perpetrator. Why would it make such error appear?
import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
TouchableHighlight,
Text
} from 'react-native';
const t = require('tcomb-form-native');
const Form = t.form.Form
const newUser = t.struct({
email: t.String,
password: t.String
})
const options = {
fields: {
email: {
autoCapitalize: 'none',
autoCorrect: false
},
password: {
autoCapitalize: 'none',
password: true,
autoCorrect: false
}
}
}
class RegisterView extends Component {
constructor(props) {
super(props)
this.state = {
value: {
email: '',
password: ''
}
}
}
componentWillUnmount() {
this.setState = {
value: {
email: '',
password: null
}
}
}
_onChange = (value) => {
this.setState({
value
})
}
_handleAdd = () => {
const value = this.refs.form.getValue();
// If the form is valid...
if (value) {
const data = {
email: value.email,
password: value.password,
}
// Serialize and post the data
const json = JSON.stringify(data);
fetch('http://localhost:3000/users/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: json
})
.then((response) => response.json())
.then(() => {
alert('Success! You may now log in.');
// Redirect to home screen
this.props.navigator.pop();
})
.catch((error) => {
alert('There was an error creating your account.');
})
.done()
} else {
// Form validation error
alert('Please fix the errors listed and try again.')
}
}
render() {
return (
<ScrollView style={styles.container}>
<Form
ref='form'
type={newUser}
options={options}
value={this.state.value}
onChange={this._onChange}
/>
<TouchableHighlight onPress={this._handleAdd}>
<Text style={[styles.button, styles.greenButton]}>Create account</Text>
</TouchableHighlight>
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
padding: 20,
flex: 1,
flexDirection: 'column'
},
button: {
borderRadius: 4,
padding: 20,
textAlign: 'center',
marginBottom: 20,
color: '#fff'
},
greenButton: {
backgroundColor: '#4CD964'
},
centering: {
alignItems: 'center',
justifyContent: 'center'
}
})
module.exports = RegisterView
According to documentation from tcomb-form-native,
tcomb-form-native ^0.5: react-native >= 0.25.0
tcomb-form-native ^0.4: react-native >= 0.20.0
tcomb-form-native ^0.3: react-native < 0.13.0
My react-native --version was
react-native-cli: 1.0.0
react-native: 0.36.0
Hence, running npm install tcomb-form-native#0.5.3 solved the issue for me.
Related
I am building a ReactNative application for both IOS and Android platforms. My app needs to read data from another device via BLE communication. I am using this package for implementing BLE communication, https://github.com/innoveit/react-native-ble-manager. I am having a problem with receiving characteristic data on IOS even though it is working as expected on the Android platform.
I have added the following to the info.plist file:
Privacy - Bluetooth Always Usage Description: App needs to use Bluetooth to receive data from WaterRower machine
I have a component that scan and list down the BLE devices as follow. It is called, BleDeviceList.js
import React, {
useState,
useEffect,
} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
NativeModules,
NativeEventEmitter,
Button,
Platform,
PermissionsAndroid,
FlatList,
TouchableHighlight,
} from 'react-native';
import {
Colors,
} from 'react-native/Libraries/NewAppScreen';
import BleManager from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
const BleDeviceList = (props) => {
const [isScanning, setIsScanning] = useState(false);
const peripherals = new Map();
const [list, setList] = useState([]);
const [ connectedDevices, setConnectedDevices ] = useState([ ]);
const [ permissionsAllowed, setPermissionsAllowed ] = useState(false)
const startScan = () => {
if (!isScanning) {
BleManager.scan([], 3, true).then((results) => {
console.log('Scanning...');
setIsScanning(true);
}).catch(err => {
console.error(err);
});
}
}
const handleStopScan = () => {
console.log('Scan is stopped');
setIsScanning(false);
}
const handleDisconnectedPeripheral = (data) => {
let peripheral = peripherals.get(data.peripheral);
if (peripheral) {
peripheral.connected = false;
peripherals.set(peripheral.id, peripheral);
setList(Array.from(peripherals.values()));
}
console.log('Disconnected from ' + data.peripheral);
}
const handleUpdateValueForCharacteristic = (data) => {
console.log('Received data from ' + data.peripheral + ' characteristic ' + data.characteristic, data.value);
}
const retrieveConnected = () => {
BleManager.getConnectedPeripherals([]).then((results) => {
if (results.length == 0) {
console.log('No connected peripherals')
}
console.log(results);
for (var i = 0; i < results.length; i++) {
var peripheral = results[i];
peripheral.connected = true;
peripherals.set(peripheral.id, peripheral);
setList(Array.from(peripherals.values()));
}
});
}
const handleDiscoverPeripheral = (peripheral) => {
console.log('Got ble peripheral', peripheral);
if (!peripheral.name) {
peripheral.name = 'NO NAME';
}
peripherals.set(peripheral.id, peripheral);
setList(Array.from(peripherals.values()));
}
const isConnected = (peripheral) => {
return connectedDevices.filter(cd => cd.id == peripheral.id).length > 0;
}
const toggleConnectPeripheral = (peripheral) => {
if (peripheral){
if (isConnected(peripheral)){
BleManager.disconnect(peripheral.id);
setConnectedDevices(connectedDevices.filter(cd => cd.id != peripheral.id))
}else{
BleManager.connect(peripheral.id).then(() => {
let tempConnnectedDevices = [ ...connectedDevices ]
tempConnnectedDevices.push(peripheral);
setConnectedDevices(tempConnnectedDevices);
props.navigation.push('BleRowingSession', { peripheral: peripheral });
let p = peripherals.get(peripheral.id);
if (p) {
p.connected = true;
peripherals.set(peripheral.id, p);
setList(Array.from(peripherals.values()));
props.navigation.push('BleDeviceServiceList', { peripheral: peripheral });
}
console.log('Connected to ' + peripheral.id);
}).catch((error) => {
console.log('Connection error', error);
});
}
}
}
useEffect(() => {
BleManager.start({showAlert: false});
bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan );
bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral );
bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic );
if (Platform.OS === 'android' && Platform.Version >= 23) {
PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
if (result) {
console.log("Permission is OK");
setPermissionsAllowed(true);
} else {
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
if (result) {
console.log("User accept");
setPermissionsAllowed(true);
} else {
console.log("User refuse");
setPermissionsAllowed(false);
}
});
}
});
} else {
setPermissionsAllowed(true)
}
return (() => {
console.log('unmount');
bleManagerEmitter.removeListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
bleManagerEmitter.removeListener('BleManagerStopScan', handleStopScan );
bleManagerEmitter.removeListener('BleManagerDisconnectPeripheral', handleDisconnectedPeripheral );
bleManagerEmitter.removeListener('BleManagerDidUpdateValueForCharacteristic', handleUpdateValueForCharacteristic );
})
}, []);
const renderConnectButton = (item) => {
if (isConnected(item)) {
return null
}
return (
<Button
title="Connect"
onPress={() => {
toggleConnectPeripheral(item)
}}
/>
)
}
const renderDisconnectButton = (item) => {
if (! isConnected(item)) {
return null
}
return (
<Button
title="Disconnect"
onPress={() => {
toggleConnectPeripheral(item)
}}
/>
)
}
const renderItem = (item) => {
const color = item.connected ? 'green' : '#fff';
return (
<TouchableHighlight>
<View style={[styles.row, {backgroundColor: color}]}>
<Text style={{fontSize: 12, textAlign: 'center', color: '#333333', padding: 10}}>{item.name}</Text>
<Text style={{fontSize: 10, textAlign: 'center', color: '#333333', padding: 2}}>RSSI: {item.rssi}</Text>
<Text style={{fontSize: 8, textAlign: 'center', color: '#333333', padding: 2, paddingBottom: 20}}>{item.id}</Text>
{renderConnectButton(item)}
{renderDisconnectButton(item)}
</View>
</TouchableHighlight>
);
}
const renderContent = () => {
if (! permissionsAllowed) {
return <Text>Bluetooth and locations permissions are required.</Text>
}
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
{global.HermesInternal == null ? null : (
<View style={styles.engine}>
<Text style={styles.footer}>Engine: Hermes</Text>
</View>
)}
<View style={styles.body}>
<View style={{margin: 10}}>
<Button
title={'Scan Bluetooth (' + (isScanning ? 'on' : 'off') + ')'}
onPress={() => startScan() }
/>
</View>
<View style={{margin: 10}}>
<Button title="Retrieve connected peripherals" onPress={() => retrieveConnected() } />
</View>
{(list.length == 0) &&
<View style={{flex:1, margin: 20}}>
<Text style={{textAlign: 'center'}}>No peripherals</Text>
</View>
}
</View>
</ScrollView>
<FlatList
data={list}
renderItem={({ item }) => renderItem(item) }
keyExtractor={item => item.id}
/>
</SafeAreaView>
</>
)
}
return (
renderContent()
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default BleDeviceList;
As you can see in the code, when the Connect button is clicked, it will redirect the user to another component that reads data from another device. The following is the BleRowingSession.js that reads the data from another device.
import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet, NativeModules, NativeEventEmitter, ScrollView } from 'react-native';
import BleManager from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
const serviceId = "00001826-0000-1000-8000-00805F9B34FB";
const characteristicId = "00002AD1-0000-1000-8000-00805F9B34FB";
let readDataCache = "";
const BleRowingSession = (props) => {
let peripheral = props.route.params.peripheral;
const [ readData, setReadData ] = useState("");
const setUpBleNotification = () => {
BleManager.retrieveServices(peripheral.id).then((peripheralData) => {
console.log('Retrieved peripheral services', peripheralData);
setTimeout(() => {
BleManager.startNotification(peripheral.id, serviceId, characteristicId).then(() => {
console.log('Started notification on ' + peripheral.id);
bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', (data) => {
readDataCache = readDataCache + "\n" + data.value.toString()
setReadData(readDataCache);
});
setTimeout(() => {
}, 500);
}).catch((error) => {
console.log('Notification error', error);
});
}, 500)
});
}
useEffect(() => {
setUpBleNotification()
}, [ ])
return (
<View style={styles.container}>
<ScrollView>
<Text>Ble Rowing Session</Text>
<Text>{readData}</Text>
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
})
export default BleRowingSession;
For now, the service id and characteristic id are hardcoded. Of course, I had to choose the right device on the first page that displays the list of BLE devices.
When I run the code, it is working as expected on the Android device, it is receiving the characteristic value. When I run the code on the actual IOS device, it is not receiving any data. But it can scan the devices and connect to them. What is wrong with my code and how can I fix it?
I'm setting up a page where I can Id with a Google account. This is my code:
import React from "react"
import { StyleSheet, Text, View, Image, Button } from "react-native"
import * as Google from "expo-google-app-auth";
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
signedIn: false,
name: "",
photoUrl: ""
}
}
signIn = async () => {
try {
const result = await Google.logInAsync({
androidClientId:
"1051966217196.apps.googleusercontent.com",
iosClientId:
"1051966217196.apps.googleusercontent.com",
scopes: ["profile", "email"]
})
if (result.type === "success") {
this.setState({
signedIn: true,
name: result.user.name,
photoUrl: result.user.photoUrl
})
} else {
console.log("cancelled")
}
} catch (e) {
console.log("error", e)
}
}
render() {
return (
<View style={styles.container}>
{this.state.signedIn ? (
<LoggedInPage name={this.state.name} photoUrl={this.state.photoUrl} />
) : (
<LoginPage signIn={this.signIn} />
)}
</View>
)
}
}
const LoginPage = props => {
return (
<View>
<Text style={styles.header}>Sign In With Google</Text>
<Button title="Sign in with Google" onPress={() => props.signIn()} />
</View>
)
}
const LoggedInPage = props => {
return (
<View style={styles.container}>
<Text style={styles.header}>Welcome:{props.name}</Text>
<Image style={styles.image} source={{ uri: props.photoUrl }} />
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
},
header: {
fontSize: 25
},
image: {
marginTop: 15,
width: 150,
height: 150,
borderColor: "rgba(0,0,0,0.2)",
borderWidth: 3,
borderRadius: 150
}
})
On Android it's ok, everything is fine but in IOS I have that mistake :
Google 400 - That's an error - Error : redirect_uri_mismatch
Where is it goes wrong? I'm new to react native so I need detailed explanations.
I changed the bundle identifier to host.exp.exponent in Google credentials and it works. It's weird because I didn't change it in app.json. But it works.
I am running this basic react native code for fetching latitude and longitude value on both android device and emulator but nowhere is the current lat/long value is being returned.
When run on emulator some value is being returned but its not the correct lat/long value, whereas on device value isn't even being return.Here is the code
import React, { Component } from 'react'
import { View, Text, Switch, StyleSheet, Button} from 'react-native'
import { createStackNavigator } from 'react-navigation';
class HomeScreen extends Component {
render() {
return (
<View style = {styles.container}>
<Button
title="Add New Outlet"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
)
}
}
class DetailsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
render(){
return(
<View style = {styles.container}>
<Text style = {styles.boldText}>
Latitude:
</Text>
<Text>
{this.state.latitude}
</Text>
<Text style = {styles.boldText}>
Longitude:
</Text>
<Text>
{this.state.longitude}
</Text>
</View>
)
}
}
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: 'center',
marginTop: 50
},
boldText: {
fontSize: 30,
color: 'red',
}
})
Please suggest any better alternatives..
For some reason navigator.geolocation is not working stable on Android devices, I changed getCurrentPosition to watchPosition and not used the third(geo_options) parameter. It worked for me.
componentDidMount() {
this.state.watchId = navigator.geolocation.watchPosition(
(position) => console.log(position),
(error) => console.log(error),
);
}
Also, you must clear watch and stop position observing when component unmounts.
componentWillUnmount() {
navigator.geolocation.clearWatch(this.state.watchId);
navigator.geolocation.stopObserving();
}
Fisrt, check android permissions:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Next:
componentDidMount() {
if (Platform.OS === "android") {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
).then(granted => {
if (granted) this._getCurrentLocation();
});
} else {
this._getCurrentLocation();
}
}
Then:
_getCurrentLocation = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
I am receiving there error "Maximum Call Stack Size Exceeded". After adding a conditional to the navigation file in my code. The stack I am using is React-Native with Expo, Redux, GraphQL and my navigation library is react-navigation. I am working on iOS simulator. This is the code that breaks the
app:
//navigations.js
if (!this.props.user.isAuthenticated) {
return <AuthenticationScreen />;
}
and this is the entirety of the navigations.js
import React, { Component } from "react";
import {
addNavigationHelpers,
StackNavigator,
TabNavigator
} from "react-navigation";
import { connect } from "react-redux";
import { FontAwesome } from "#expo/vector-icons";
import HomeScreen from "./screens/HomeScreen";
import ExploreScreen from "./screens/ExploreScreen";
import FavoritesScreen from "./screens/FavoritesScreen";
import ProfileScreen from "./screens/ProfileScreen";
import AuthenticationScreen from "./screens/AuthenticationScreen";
import { colors } from "./utils/constants";
const TAB_ICON_SIZE = 20;
const Tabs = TabNavigator(
{
Home: {
screen: HomeScreen,
navigationOptions: () => ({
headerTitle: "Saga",
tabBarIcon: ({ tintColor }) => (
<FontAwesome size={TAB_ICON_SIZE} color={tintColor} name="home" />
)
})
},
Explore: {
screen: ExploreScreen,
navigationOptions: () => ({
headerTitle: "Explore",
tabBarIcon: ({ tintColor }) => (
<FontAwesome size={TAB_ICON_SIZE} color={tintColor} name="search" />
)
})
},
Favorites: {
screen: FavoritesScreen,
navigationOptions: () => ({
headerTitle: "Favorites",
tabBarIcon: ({ tintColor }) => (
<FontAwesome
size={TAB_ICON_SIZE}
color={tintColor}
name="file-video-o"
/>
)
})
},
Profile: {
screen: ProfileScreen,
navigationOptions: () => ({
headerTitle: "Profile",
tabBarIcon: ({ tintColor }) => (
<FontAwesome size={TAB_ICON_SIZE} color={tintColor} name="user" />
)
})
}
},
{
lazy: true,
tabBarPosition: "bottom",
swipeEnabled: false,
tabBarOptions: {
showIcon: true,
showLabel: false,
activeTintColor: colors.PRIMARY,
inactiveTintColor: colors.LIGHT_GRAY,
style: {
backgroundColor: colors.BASE_GRAY,
height: 50,
paddingVertical: 5
}
}
}
);
const AppMainNav = StackNavigator(
{
Home: {
screen: Tabs
}
},
{
cardStyle: {
backgroundColor: "#F1F6FA"
},
navigationOptions: () => ({
headerStyle: {
backgroundColor: colors.BASE_GRAY
},
headerTitleStyle: {
fontWeight: "bold",
fontSize: 24,
color: colors.BLUE
}
})
}
);
class AppNavigator extends Component {
render() {
const nav = addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.nav
});
if (!this.props.user.isAuthenticated) {
return <AuthenticationScreen />;
}
return <AppMainNav navigation={nav} />;
}
}
export default connect(state => ({
nav: state.nav,
user: state.user
}))(AppNavigator);
export const router = AppMainNav.router;
For good measure this is the user.js reducer:
const initialState = {
token: null,
isAuthenticated: false,
info: null
};
export default (state = initialState, action) => {
switch (action.type) {
default:
return state;
}
};
I can't see what would be causing an infinite loop.
Update #1
AuthenticationScreen.js (Minus Imports)
const Root = styled.View``;
const T = styled.Text``;
class AuthenticationScreen extends Component {
state = {};
render() {
return (
<Root>
<T>AuthenticationScreen</T>
</Root>
);
}
}
export default AuthenticationScreen;
As I understand it, you've isolated the problem to this code...
if (!this.props.user.isAuthenticated) {
return <AuthenticationScreen />;
}
return <AppMainNav navigation={nav} />;
And if you remove...
if (!this.props.user.isAuthenticated) {
return <AuthenticationScreen />;
}
it works fine, which means <AppMainNav> must be fine. So the infinite loop must be in your <AuthenticationScreen /> code.
I use ReactNative to develop my iOS APP,to realize the QRCode scanner function,i took the react-native-camera component which provide the barcode scanner function to my project.everything goes all right,but when i had succeed in recognizing a QRCode,next time i use the model,the screen just got frozen,seems like the app goes crashed. something interesting that as the screen is frozen,and once the model cancelled from the left button of navigation,The module can work properly.
I'm not sure whether it's a inner bug of NavigatorIOS,or just the bug of react-native-camera itself.
here is the QRCode component code:
'use strict';
var React = require('react-native');
var Dimensions = require('Dimensions');
var {
StyleSheet,
View,
Text,
TouchableOpacity,
VibrationIOS,
Navigator,
} = React;
var Camera = require('react-native-camera');
var { width, height } = Dimensions.get('window');
var QRCodeScreen = React.createClass({
propTypes: {
cancelButtonVisible: React.PropTypes.bool,
cancelButtonTitle: React.PropTypes.string,
onSucess: React.PropTypes.func,
onCancel: React.PropTypes.func,
},
getDefaultProps: function() {
return {
cancelButtonVisible: false,
cancelButtonTitle: 'Cancel',
barCodeFlag: true,
};
},
_onPressCancel: function() {
var $this = this;
requestAnimationFrame(function() {
$this.props.navigator.pop();
if ($this.props.onCancel) {
$this.props.onCancel();
}
});
},
_onBarCodeRead: function(result) {
var $this = this;
if (this.props.barCodeFlag) {
this.props.barCodeFlag = false;
setTimeout(function() {
VibrationIOS.vibrate();
$this.props.navigator.pop();
$this.props.onSucess(result.data);
}, 1000);
}
},
render: function() {
var cancelButton = null;
if (this.props.cancelButtonVisible) {
cancelButton = <CancelButton onPress={this._onPressCancel} title={this.props.cancelButtonTitle} />;
}
return (
<Camera onBarCodeRead={this._onBarCodeRead} style={styles.camera}>
<View style={styles.rectangleContainer}>
<View style={styles.rectangle}/>
</View>
{cancelButton}
</Camera>
);
},
});
var CancelButton = React.createClass({
render: function() {
return (
<View style={styles.cancelButton}>
<TouchableOpacity onPress={this.props.onPress}>
<Text style={styles.cancelButtonText}>{this.props.title}</Text>
</TouchableOpacity>
</View>
);
},
});
var styles = StyleSheet.create({
camera: {
width:width,
height: height,
alignItems: 'center',
justifyContent: 'center',
},
rectangleContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent',
},
rectangle: {
height: 250,
width: 250,
borderWidth: 2,
borderColor: '#00FF00',
backgroundColor: 'transparent',
},
cancelButton: {
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: 'white',
borderRadius: 3,
padding: 15,
width: 100,
marginBottom: 10,
},
cancelButtonText: {
fontSize: 17,
fontWeight: '500',
color: '#0097CE',
},
});
module.exports = QRCodeScreen;
And In another Component I push this qrCode to the new sence:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
NavigatorIOS,
AlertIOS,
Navigator,
} = React;
var QRCodeScreen = require('./QRCodeScreen');
var cameraApp = React.createClass({
render: function() {
return (
<NavigatorIOS
style={styles.container}
initialRoute={{
title: 'Index',
backButtonTitle: 'Back',
component: Index,
}}
/>
);
}
});
var Index = React.createClass({
render: function() {
return (
<View style={styles.contentContainer}>
<TouchableOpacity onPress={this._onPressQRCode}>
<Text>Read QRCode</Text>
</TouchableOpacity>
</View>
);
},
_onPressQRCode: function() {
this.props.navigator.push({
component: QRCodeScreen,
title: 'QRCode',
passProps: {
onSucess: this._onSucess,
},
});
},
// onPressCancel:function(){
//
// this.props.navigator.getContext(this).pop();
//
// },
_onSucess: function(result) {
AlertIOS.alert('Code Context', result, [{text: 'Cancel', onPress: ()=>console.log(result)}]);
// console.log(result);
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
contentContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}
});
AppRegistry.registerComponent('Example', () => cameraApp);
Any answer will be helpful!
I think it's a inner bug of NavigatorIOS, or maybe just sth else wrong.
Blew is my code, it is ok.
'use strict';
const React = require('react-native');
const {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
Navigator,
} = React;
var QRCodeScreen = require('./QRCodeScreen');
const CameraApp = () => {
const renderScene = (router, navigator) => {
switch (router.name) {
case 'Index':
return <Index navigator={navigator}/>;
case 'QRCodeScreen':
return <QRCodeScreen
onSucess={router.onSucess}
cancelButtonVisible={router.cancelButtonVisibl}
navigator={navigator}
/>;
}
}
return (
<Navigator
style={styles.container}
initialRoute={{
name: 'Index',
}}
renderScene={renderScene}
/>
);
};
const Index = ({navigator}) => {
const onPressQRCode = () => {
navigator.push({
name: 'QRCodeScreen',
title: 'QRCode',
onSucess: onSucess,
cancelButtonVisible: true,
});
};
const onSucess = (result) => {
console.log(result);
};
return (
<View style={styles.contentContainer}>
<TouchableOpacity onPress={onPressQRCode}>
<Text>Read QRCode</Text>
</TouchableOpacity>
</View>
);
};
module.exports = CameraApp;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
contentContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}
});
you can try Library react native qrcode
https://github.com/moaazsidat/react-native-qrcode-scanner. on me ,
its run. you can try . in ios and android.