1584762447
If you’ve come to JavaScript in recent years and are a user of the newer front-end frameworks or libraries like React, import
and export
will be familiar to you. For those of us who weren’t watching the new module syntax being introduced in ES6, you may have just got to a level of understanding between the difference of a named and a default export, but you may have missed the nuance on the ability to alias imports and why this could be important.
A module (as an example, a Javascript file like my-module.js) can export functionality or objects from itself for use in other modules. This is fundamental in adhering to a bunch of coding principles, like code-reuse and separation of concerns. In modules, we find exports in two ways:
export
on different functions or objects.export default
on a single function or object.When a module needs to import functionality from another module, it has a number of options available:
import * from "my-module.js"
import { func1, obj2 } from "my-module.js"
import func from "my-module.js"
import "my-module.js"
import("my-module.js").then((module) => { //...do something })
For most use cases, especially if you’re a React developer, importing named and default exports will be what you’ll primarily use.
There are use cases where you’ll import into the current module scopes (like project constants defined in a JS object) or dynamic import (for code-splitting) but more often than not it’s just the default and named exports that you’ll focus on.
Import aliases are where you take your standard import, but instead of using a pre-defined name by the exporting module, you use a name that is defined in the importing module.
There may a be time where you find yourself requiring imports from multiple different modules but contain exports named the same. Javascript doesn’t like this.
Failed to compile.
/Users/gregbyrne/Project/One/src/pages/index.js
SyntaxError: /Users/gregbyrne/Project/One/src/pages/index.js: Identifier 'Card' has already been declared (6:9)
4 | import { Button } from '../components/button'
5 | import { Card } from '../components/card'
> 6 | import { Card } from 'react-native-elements'
A common example where you may come across this problem is providing a project-level abstraction over a dependency.
For example, using a component library directly in your screens can make your project highly-coupled with the implementation of that component library. In the future, your project may switch that dependency and if it wasn’t abstracted, you may find it isn’t as simple as switching imports. That’s where project abstractions come to the rescue.
// Card.js in project/src/components/card
import { Card } from "cool-component-library"
const Card = () => (
// abstraction over cool-component-library card
// suitable for your project needs
)
const ListCard = () => (
// like above
)
export { Card, ListCard }
// ---
// Index.js in project/src/pages
import { Card } from '.../components/card'
// ... index page code
The eagle eyed reading this would see from the above that Card.js
won’t compile because of the declaration error as before.
So we come full circle to Import aliases. These will allow you to import similarly named exports for use within your module.
When importing from a named export, e.g.
// my-module.js
// ... code ..
export { Something1, Something2}
You can alias the import using as
:
import { Something1 as MySomething } from "my-module.js"
For importing default exports, e.g.
// my-module.js
// ... code ..
export default Something
You can alias the import directly:
import MySomething from "my-module.js"
With the example above on the Card
component project abstraction, we can solve the compile error by aliasing the named export.
// Card.js in project/src/components/card
import { Card as CoolCard } from "cool-component-library"
const Card = () => (
// abstraction over cool-component-library card
// suitable for your project needs
)
const ListCard = () => (
// like above
)
export { Card, ListCard }
If it happens to be a default export, we can still alias it.
// Button.js in project/src/components/button
import CoolButton from "cool-component-library-button"
const MyButton = () => (
// code
)
export default MyButton
// ---
// Index.js in project/src/pages
import Button from '.../components/button/Button.js'
// ... index page code
Thank you for reading!
#javascript #react #development
1656977400
Hoy sigo compartiendo mi experiencia con el Módulo Nativo y C++.
Dado que veremos muchas bibliotecas C/C++ escribiendo para las plataformas móviles, debemos implementarlas en nuestra aplicación iOS o React Native. Por eso quiero escribir un artículo sobre cómo exportar una función de C++ a React Native, que es fácil de entender y ahorra tiempo a los principiantes. Comenzaré con una nueva aplicación nativa de reacción.
npx react-native init NativeModules
Cree un nuevo archivo C++ y asígnele un nombreCpp_to_RN.cpp
Cuando creamos un nuevo archivo C++, Xcode creará un archivo de encabezado Cpp_to_RN.hpp
para nosotros
Primero, abra el archivo " Cpp_to_RN.hpp
" y cree una clase que incluya una función sin el cuerpo.
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
Luego abre el Cpp_to_RN.cpp
archivo y escribe una función simple “ sayHello()
”
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
Para envolver los archivos C++ y exportarlos al lado IOS (swift)
una. Cree un archivo Objective C y asígnele un nombreCpp_to_RN.m
Renombrar el Cpp_to_RN.m
a Cpp_to_RN.mm
b. Abra el WrapCpp_to_RN.mm
archivo y escriba el contenido del cuerpo que envolverá la función sayHello
del archivo C++.
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
C. Cree un archivo de encabezado y asígnele un nombreWrapCpp_to_RN.h
Exportar la wrapSayHello
función al archivo Swift
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Para exportar la función C++ a React Native
una. Cree un archivo Swift y asígnele un nombreSendCpp_to_RN.swift
Nota: Xcode nos pedirá que creemos un NativeModules-Bridging-Header.h
archivo para nosotros.
Crear una clase SendCpp_to_RN
y declararla comoNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Escribir una función requiresMainQueueSetup()
para evitar advertencias cuando ejecutamos la aplicación.
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Escriba una función para envolver el WrapCpp_to_RN()
fromWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
b. Exporte una función de ajuste en un archivo Swift a React Native
Cree un archivo Objective C para exportar la clase Swift y su función usandoCallback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
C. Conecte Swift a React Native, abra el NativeModules-Bridging-Header.h
archivo
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Llame a la clase Swift y sus funciones
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
Y listo, solo ejecuta la aplicación
react-native run-ios
O simplemente haga clic en el botón "ejecutar" en Xcode y vea lo que hemos hecho.
Espero que mi artículo te sea útil, gracias por tu tiempo de lectura.
1675797780
A debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.
LLDebugTool is a debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.
LLDebugToolSwift is the extension of LLDebugTool, it provide swift interface for LLDebugTool, LLDebugToolSwift will release with LLDebugTool at same time.
If your project is a Objective-C project, you can use LLDebugTool
, if your project is a Swift project or contains swift files, you can use LLDebugToolSwift
.
Choose LLDebugTool for your next project, or migrate over your existing projects—you'll be happy you did! 🎊🎊🎊
cocoadocs.org
cause cocoadocs.org
to disable the access to LLDebugTool
, so this function is removed.Always check the network request or view log information for certain events without having to run under XCode. This is useful in solving the testers' problems.
Easier filtering and filtering of useful information.
Easier analysis of occasional problems.
Easier analysis of the cause of the crash.
Easier sharing, previewing, or removing sandbox files, which can be very useful in the development stage.
Easier observe app's memory, CPU, FPS and other information.
Take screenshots, tag and share.
More intuitive view of view structure and dynamic modify properties.
Determine UI elements and colors in your App more accurately.
Easy access to and comparison of point information.
Easy access to element borders and frames.
Quick entry for html.
Mock location at anytime.
CocoaPods is the recommended way to add LLDebugTool
to your project.
Objective - C
- Add a pod entry for LLDebugTool to your Podfile
pod 'LLDebugTool' , '~> 1.0'
.- If only you want to use it only in Debug mode, Add a pod entry for LLDebugTool to your Podfile
pod 'LLDebugTool' , '~> 1.0' ,:configurations => ['Debug']
, Details also see Wiki/Use in Debug environment. If you want to specify the version, use aspod 'LLDebugTool' , '1.3.8.1' ,:configurations => ['Debug']
.- The recommended approach is to use multiple targets and only add
pod 'LLDebugTool', '~> 1.0'
to Debug Target. This has the advantage of not contamiling the code in the Product environment and can be integrated into the App in the Archive Debug environment (if:configurations => ['Debug']
, it can only run through XCode. It is not possible to Archive as an App).- Install the pod(s) by running
pod install
. If you can't searchLLDebugTool
or you can't find the newest release version, runningpod repo update
beforepod install
.- Include LLDebugTool wherever you need it with
#import "LLDebug.h"
or you can write#import "LLDebug.h"
in your .pch in your .pch file.
Swift
- Add a pod entry for LLDebugToolSwift to your Podfile
pod 'LLDebugToolSwift' , '~> 1.0'
.- If only you want to use it only in Debug mode, Add a pod entry for LLDebugToolSwift to your Podfile
pod 'LLDebugToolSwift' , '~> 1.0' ,:configurations => ['Debug']
, Details also see Wiki/Use in Debug environment. If you want to specify the version, use aspod 'LLDebugToolSwift' , '1.3.8.1' ,:configurations => ['Debug']
.- The recommended approach is to use multiple targets and only add
pod 'LLDebugToolSwift', '~> 1.0'
to Debug Target. This has the advantage of not contamiling the code in the Product environment and can be integrated into the App in the Archive Debug environment (if:configurations => ['Debug']
, it can only run through XCode. It is not possible to Archive as an App).- Must be added in the Podfile
use_frameworks!
.- Install the pod(s) by running
pod install
. If you can't searchLLDebugToolSwift
or you can't find the newest release version, runningpod repo update
beforepod install
.- Include LLDebugTool wherever you need it with
import "LLDebugToolSwift
.
Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
Objective - C
To integrate LLDebugTool into your Xcode project using Carthage, specify it in your
Cartfile
:
github "LLDebugTool"
Run
carthage
to build the framework and drag the builtLLDebugTool.framework
into your Xcode project.
Swift
To integrate LLDebugToolSwift into your Xcode project using Carthage, specify it in your
Cartfile
:
github "LLDebugToolSwift"
Run
carthage
to build the framework and drag the builtLLDebugToolSwift.framework
into your Xcode project.
Alternatively you can directly add the source folder named LLDebugTool. to your project.
Objective - C
- Download the latest code version or add the repository as a git submodule to your git-tracked project.
- Open your project in Xcode, then drag and drop the source folder named
LLDebugTool
. When you are prompted to "Choose options for adding these files", be sure to check the "Copy items if needed".- Integrated FMDB to your project,FMDB is an Objective-C wrapper around SQLite.
- Integrated Masonry to your project, Masonry is an Objective-C constraint library. There are no specific version requirements, but it is recommended that you use the latest version.
- Include LLDebugTool wherever you need it with
#import "LLDebug.h"
or you can write#import "LLDebug.h"
in your .pch in your .pch file.
Swift
- Download the LLDebugTool latest code version or add the repository as a git submodule to your git-tracked project.
- Download the LLDebugToolSwift latest code version or add the repository as a git submodule to your git-tracked project.
- Open your project in Xcode, then drag and drop the source folder named
LLDebugTool
andLLDebugToolSwift
. When you are prompted to "Choose options for adding these files", be sure to check the "Copy items if needed".- Integrated FMDB to your project,FMDB is an Objective-C wrapper around SQLite.
- Integrated Masonry to your project, Masonry is an Objective-C constraint library. There are no specific version requirements, but it is recommended that you use the latest version.
- Include LLDebugTool wherever you need it with
import LLDebugToolSwift"
.
You need to start LLDebugTool at "application:(UIApplication * )application didFinishLaunchingWithOptions:(NSDictionary * )launchOptions", Otherwise you will lose some information.
If you want to configure some parameters, must configure before "startWorking". More config details see LLConfig.h.
Quick Start
In Objective-C
#import "AppDelegate.h"
#import "LLDebug.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// The default color configuration is green background and white text color.
// Start working.
[[LLDebugTool sharedTool] startWorking];
// Write your project code here.
return YES;
}
In Swift
import LLDebugToolSwift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// ####################### Start LLDebugTool #######################//
// Use this line to start working.
LLDebugTool.shared().startWorking()
// Write your project code here.
return true
}
Start With Custom Config
In Objective-C
#import "AppDelegate.h"
#import "LLDebug.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Start working with config.
[[LLDebugTool sharedTool] startWorkingWithConfigBlock:^(LLConfig * _Nonnull config) {
//####################### Color Style #######################//
// Uncomment one of the following lines to change the color configuration.
// config.colorStyle = LLConfigColorStyleSystem;
// [config configBackgroundColor:[UIColor orangeColor] primaryColor:[UIColor whiteColor] statusBarStyle:UIStatusBarStyleDefault];
//####################### User Identity #######################//
// Use this line to tag user. More config please see "LLConfig.h".
config.userIdentity = @"Miss L";
//####################### Window Style #######################//
// Uncomment one of the following lines to change the window style.
// config.entryWindowStyle = LLConfigEntryWindowStyleNetBar;
}];
return YES;
}
In Swift
import LLDebugToolSwift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Start working with config.
LLDebugTool.shared().startWorking { (config) in
//####################### Color Style #######################//
// Uncomment one of the following lines to change the color configuration.
// config.colorStyle = .system
// config.configBackgroundColor(.orange, textColor: .white, statusBarStyle: .default)
//####################### User Identity #######################//
// Use this line to tag user. More config please see "LLConfig.h".
config.userIdentity = "Miss L";
//####################### Window Style #######################//
// Uncomment one of the following lines to change the window style.
// config.windowStyle = .netBar
//####################### Features #######################//
// Uncomment this line to change the available features.
// config.availables = .noneAppInfo
}
return true
}
You don't need to do anything, just call the "startWorking" will monitoring most of network requests, including the use of NSURLSession, NSURLConnection and AFNetworking. If you find that you can't be monitored in some cases, please open an issue and tell me.
Print and save a log. More log macros details see LLDebugToolMacros.h.
Save Log
In Objective-C
#import "LLDebug.h"
- (void)testNormalLog {
// Insert an LLog where you want to print.
LLog(@"Message you want to save or print.");
}
In Swift
import LLDebugToolSwift
func testNormalLog() {
// Insert an LLog where you want to print.
LLog.log(message: "Message you want to save or print.")
}
Save Log with event and level
In Objective-C
#import "LLDebug.h"
- (void)testEventErrorLog {
// Insert an LLog_Error_Event where you want to print an event and level log.
LLog_Error_Event(@"The event that you want to mark. such as bugA, taskB or processC.",@"Message you want to save or print.");
}
In Swift
import LLDebugToolSwift
func testEventErrorLog() {
// Insert an LLog_Error_Event where you want to print an event and level log.
LLog.errorLog(message: "Message you want to save or print.", event: "The event that you want to mark. such as bugA, taskB or processC.")
}
You don't need to do anything, just call the "startWorking" to intercept the crash, store crash information, cause and stack informations, and also store the network requests and log informations at the this time.
LLDebugTool monitors the app's CPU, memory, and FPS. At the same time, you can also quickly check the various information of the app.
LLDebugTool provides a quick way to view and manipulate sandbox, you can easily delete the files/folders inside the sandbox, or you can share files/folders by airdrop elsewhere. As long as apple supports this file format, you can preview the files directly in LLDebugTool.
LLDebugTool provides a screenshot and allows for simple painting and marking that can be easily recorded during testing or while the UI designers debugs the App.
LLDebugTool provides a view structure tool for viewing or modify elements' properties and information in non-debug mode.
LLDebugTool provides a magnify tool for magnifying local uis and viewing color values at specified pixel.
LLDebugTool provides a convenient tools to display touch point information.
LLDebugTool provides a function to display element border, convenient to see the view's frame.
LLDebugTool can debug HTML pages through WKWebView
, UIWebView
or your customized ViewController
in your app at any time.
LLDebugTool provides a function to mock location at anytime.
LLDebugTool works on iOS 8+ and requires ARC to build. It depends on the following Apple frameworks, which should already be included with most Xcode templates:
UIKit
Foundation
SystemConfiguration
Photos
QuickLook
CoreTelephony
CoreLocation
MapKit
AVKit
LLDebug.h
Public header file. You can refer it to the pch file.
DebugTool
LLDebugTool
Used to start and stop LLDebugTool, you need to look at it.
LLConfig
Used for the custom color , size , identification and other information. If you want to configure anything, you need to focus on this file.
LLDebugToolMacros.h
Quick macro definition file.
Components
Network
Used to monitoring network request.Log
Used to quick print and save log.Crash
Used to collect crash information when an App crashes.AppInfo
Use to monitoring app's properties.Sandbox
Used to view and operate sandbox files.Screenshot
Used to process and display screenshots.Hierarchy
Used to process and present the view structure.Magnifier
Used for magnifying glass function.Ruler
Used to ruler function.Widget Border
User to widget border function.Function
Used to show functions.Html
Used to dynamic test web view.Location
Used to mock location.Setting
Used to dynamically set configs.A brief summary of each LLDebugTool release can be found in the CHANGELOG.
Author: HDB-Li
Source Code: https://github.com/HDB-Li/LLDebugTool
License: View license
1656979200
Aujourd'hui, je continue à partager mon expérience avec le module natif et C++.
Comme nous verrons beaucoup de bibliothèques C/C++ écrire pour les plates-formes mobiles, nous devons les implémenter dans notre application iOS ou React Native. C'est pourquoi je souhaite écrire un article sur la façon d'exporter une fonction de C++ vers React Native, ce qui est facile à comprendre et fait gagner du temps aux débutants. Je vais commencer avec une nouvelle application native réactive
npx react-native init NativeModules
Créez un nouveau fichier C++ et nommez-leCpp_to_RN.cpp
Lorsque nous créons un nouveau fichier C++, Xcode créera un fichier d'en-tête Cpp_to_RN.hpp
pour nous
Tout d'abord, ouvrez le fichier " Cpp_to_RN.hpp
" et créez une classe qui inclut une fonction sans le corps.
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
Ouvrez ensuite le Cpp_to_RN.cpp
fichier et écrivez une fonction simple " sayHello()
"
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
Pour envelopper les fichiers C++ et les exporter vers le côté IOS (swift)
un. Créez un fichier Objective C et nommez-leCpp_to_RN.m
Renommez le Cpp_to_RN.m
en Cpp_to_RN.mm
b. Ouvrez le WrapCpp_to_RN.mm
fichier et écrivez le contenu du corps qui encapsulera la fonction sayHello
à partir du fichier C++.
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
c. Créez un fichier d'en-tête et nommez-leWrapCpp_to_RN.h
Exporter la wrapSayHello
fonction vers le fichier Swift
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Pour exporter la fonction C++ vers React Native
un. Créez un fichier Swift et nommez-leSendCpp_to_RN.swift
Remarque : Xcode nous demandera de créer un NativeModules-Bridging-Header.h
fichier pour nous.
Créez une classe SendCpp_to_RN
et déclarez-la commeNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Écrire une fonction requiresMainQueueSetup()
pour empêcher l'avertissement lorsque nous exécutons l'application
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Ecrire une fonction pour envelopper le WrapCpp_to_RN()
fromWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
b. Exporter une fonction wrap dans un fichier Swift vers React Native
Créez un fichier Objective C pour exporter la classe Swift et sa fonction à l'aide deCallback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
c. Connectez Swift à React Native, ouvrez le NativeModules-Bridging-Header.h
fichier
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Appelez la classe Swift et ses fonctions
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
Et nous avons terminé, il suffit de lancer l'application
react-native run-ios
Ou cliquez simplement sur le bouton "exécuter" sur Xcode et voyez ce que nous avons fait.
J'espère que mon article vous sera utile, merci pour le temps de lecture.
1656982800
Hoje, continuo compartilhando minha experiência com o Módulo Nativo e C++.
Como veremos muitas bibliotecas C/C++ escrevendo para plataformas móveis, precisamos implementá-las em nosso aplicativo iOS ou React Native. É por isso que quero escrever um artigo sobre como exportar uma função de C++ para React Native, que é fácil de entender e economiza tempo para iniciantes. Vou começar com um novo aplicativo nativo de reação
npx react-native init NativeModules
Crie um novo arquivo C++ e nomeie-oCpp_to_RN.cpp
Quando criamos um novo arquivo C++, o Xcode criará um arquivo de cabeçalho Cpp_to_RN.hpp
para nós
Primeiro, abra o arquivo “ Cpp_to_RN.hpp
” e crie uma classe que inclua uma função sem o corpo.
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
Em seguida, abra o Cpp_to_RN.cpp
arquivo e escreva uma função simples “ sayHello()
”
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
Para encapsular os arquivos C++ e exportá-los para o lado IOS (swift)
uma. Crie um arquivo Objective C e nomeie-oCpp_to_RN.m
Renomeie o Cpp_to_RN.m
para Cpp_to_RN.mm
b. Abra o WrapCpp_to_RN.mm
arquivo e escreva o conteúdo do corpo que envolverá a função sayHello
do arquivo C++.
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
c. Crie um arquivo de cabeçalho e nomeie-oWrapCpp_to_RN.h
Exporte a wrapSayHello
função para o arquivo Swift
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Para exportar a função C++ para React Native
uma. Crie um arquivo Swift e nomeie-oSendCpp_to_RN.swift
Observação: o Xcode nos pedirá para criar um NativeModules-Bridging-Header.h
arquivo para nós.
Crie uma classe SendCpp_to_RN
e declare-a comoNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Escreva uma função requiresMainQueueSetup()
para evitar avisos quando executamos o aplicativo
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Escreva uma função para envolver o WrapCpp_to_RN()
fromWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
b. Exporte uma função wrap no arquivo Swift para React Native
Crie um arquivo Objective C para exportar a classe Swift e sua função usandoCallback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
c. Conecte o Swift ao React Native, abra o NativeModules-Bridging-Header.h
arquivo
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Chame a classe Swift e suas funções
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
E pronto, basta executar o aplicativo
react-native run-ios
Ou apenas clique no botão “executar” no Xcode e veja o que fizemos.
Espero que meu artigo seja útil para você, obrigado pelo tempo de leitura.
1656981060
今日も、ネイティブモジュールとC++での経験を共有し続けています。
多くのC/C ++ライブラリがモバイルプラットフォーム用に作成されているので、それらをiOSまたはReactNativeアプリケーションに実装する必要があります。そのため、関数をC++からReactNativeにエクスポートする方法についての記事を書きたいと思います。これは、理解しやすく、初心者の時間を節約できます。新しいreactネイティブアプリケーションから始めます
npx react-native init NativeModules
新しいC++ファイルを作成し、名前を付けますCpp_to_RN.cpp
新しいC++ファイルを作成すると、XcodeはヘッダーファイルCpp_to_RN.hpp
を作成します
まず、「Cpp_to_RN.hpp
」ファイルを開き、本体のない関数を含むクラスを作成します。
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
次に、ファイルを開いてCpp_to_RN.cpp
、単純な関数「sayHello()
」を記述します。
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
C ++ファイルをラップしてIOS(swift)側にエクスポートするには
a。ObjectiveCファイルを作成して名前を付けますCpp_to_RN.m
名前をに変更Cpp_to_RN.m
します Cpp_to_RN.mm
b。ファイルを開き、C++ファイルからWrapCpp_to_RN.mm
関数をラップする本文のコンテンツを記述します。sayHello
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
c。ヘッダーファイルを作成し、名前を付けますWrapCpp_to_RN.h
wrapSayHello
関数をSwiftファイルにエクスポートします
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
C++関数をReactNativeにエクスポートするには
a。Swiftファイルを作成し、名前を付けますSendCpp_to_RN.swift
注:Xcodeは、NativeModules-Bridging-Header.h
ファイルを作成するように要求します。
クラスSendCpp_to_RN
を作成し、次のように宣言しますNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
requiresMainQueueSetup()
アプリケーション実行時の警告を防ぐ関数を作成する
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
WrapCpp_to_RN()
fromをラップする関数を記述しますWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
b。Swiftファイルのラップ関数をReactNativeにエクスポートします
を使用してSwiftクラスとその関数をエクスポートするObjectiveCファイルを作成しますCallback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
c。SwiftをReactNativeに接続し、NativeModules-Bridging-Header.h
ファイルを開きます
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Swiftクラスとその関数を呼び出す
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
これで完了です。アプリケーションを実行するだけです。
react-native run-ios
または、Xcodeの「実行」ボタンをクリックして、実行内容を確認してください。
私の記事がお役に立てば幸いです。お読みいただきありがとうございます。