68 lines
2 KiB
TypeScript
68 lines
2 KiB
TypeScript
import { NewAppScreen } from '@react-native/new-app-screen'
|
|
import { useEffect, useState } from 'react'
|
|
import { StatusBar, Text, StyleSheet, useColorScheme, ScrollView, Button, Alert } from 'react-native'
|
|
import { NativeEventEmitter, NativeModules } from 'react-native'
|
|
|
|
const { Emitter, TestingServiceModule } = NativeModules
|
|
|
|
import { requireNativeComponent } from 'react-native'
|
|
import type { StyleProp, ViewStyle } from 'react-native'
|
|
|
|
type CustomButtonProps = {
|
|
style?: StyleProp<ViewStyle>
|
|
}
|
|
const CustomButton = requireNativeComponent<CustomButtonProps>('CustomButton')
|
|
const BaseButton = requireNativeComponent<CustomButtonProps>('BaseButton')
|
|
|
|
export default function App() {
|
|
const isDarkMode = useColorScheme() === 'dark'
|
|
const [message, setMessage] = useState<string|null>(null)
|
|
const [color, setColor] = useState("#FFF")
|
|
|
|
|
|
const onPress = async () => {
|
|
if (!TestingServiceModule?.greet) {
|
|
Alert.alert('Module not found', 'MyNativeModule is not linked or not exported.')
|
|
return
|
|
}
|
|
try {
|
|
const result = await TestingServiceModule.greet('John')
|
|
setMessage(result);
|
|
} catch (error) {
|
|
console.error(error)
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
const emitter = new NativeEventEmitter(Emitter);
|
|
const subscription = emitter.addListener('onMessage', (event) => {
|
|
if (event?.message) {
|
|
setMessage(event.message)
|
|
|
|
if (event?.message == "hello from Swift!") {
|
|
setColor("#00F")
|
|
}
|
|
}
|
|
})
|
|
|
|
return () => {
|
|
subscription.remove()
|
|
};
|
|
}, [])
|
|
|
|
return (
|
|
<ScrollView style={{...styles.container, backgroundColor: color}}>
|
|
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
|
|
<Text>{message ?? 'Waiting for message...'}</Text>
|
|
<CustomButton style={{ height: 70 }} />
|
|
<BaseButton style={{ height: 70 }} />
|
|
<Button title="Call Swift greet()" onPress={onPress} />
|
|
</ScrollView>
|
|
);
|
|
}
|
|
|
|
const styles = StyleSheet.create({
|
|
container: {
|
|
flex: 1,
|
|
},
|
|
})
|