React Native App Development Company in USA | Page 3
Import Foundation
@objc(Bulb)
Class Bulb : NSObject {
@objc
Static var isOn = false
@objc
Func turnOn(){
Bulb.isOn = true
Print (“Bulb is now ON”)
}
}
COPY
We have created a Bulb class which is inherited from NSObject. The base class of most Objective-C class ranking is
NSObject, from which subclasses acquire a basic interface to the runtime system and therefore the capability to behave
as Objective-C objects. we will see that we've used @objc before a function and sophistication , this may make that class,
function or object available to Objective C
React Native won't expose any function of Bulb to React JavaScript unless explicitly done. to try to do so we've used
RCT_EXPORT_METHOD() macro. So we've exposed the Bulb class and turnOn function to our Javascript code. Since Swift
object is converted to Javascript object, there's a kind of conversation. RCT_EXPORT_METHOD supports all standard
JSON object types:
NSString to string
NSInteger, float, double, CGFloat, NSNumber to number
BOOL to boolean
NSArray to array
NSDictionary to object with string keys and values of any type from this list
RCTResponseSenderBlock to function
Now let’s modernize JavaScript code and approach this Bulb class from our React component. to try to to so open App.js
and update with the subsequent code:
Export default class App extends Component{
turnOn = () => {
NativeModules.Bulb.turnOn();
}
render(){
return(
Welcome to Light App !!