Passing events from SwiftUI Button created by RN and getting it back to SwiftUI

This commit is contained in:
Artur Gurgul 2025-08-03 12:07:14 +02:00
parent 41081b5084
commit 1a9884e0e9
6 changed files with 24 additions and 14 deletions

12
App.tsx
View file

@ -1,6 +1,6 @@
import { NewAppScreen } from '@react-native/new-app-screen'
import { useEffect, useState } from 'react'
import { StatusBar, Text, StyleSheet, useColorScheme, View } from 'react-native'
import { StatusBar, Text, StyleSheet, useColorScheme, ScrollView } from 'react-native'
import { NativeEventEmitter, NativeModules } from 'react-native'
const { Emitter } = NativeModules
@ -16,12 +16,17 @@ const BaseButton = requireNativeComponent<CustomButtonProps>('BaseButton')
export default function App() {
const isDarkMode = useColorScheme() === 'dark'
const [message, setMessage] = useState(null)
const [color, setColor] = useState("#FFF")
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")
}
}
})
@ -31,13 +36,12 @@ export default function App() {
}, [])
return (
<View style={styles.container}>
<ScrollView style={{...styles.container, backgroundColor: color}}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<Text>{message ?? 'Waiting for message...'}</Text>
<CustomButton style={{ height: 200 }} />
<BaseButton style={{ height: 200 }} />
<NewAppScreen templateFileName="App.tsx" />
</View>
</ScrollView>
);
}