1675946917
The Importance of React in Building Mobile-First Websites and Applications
With the increasing popularity of mobile devices and their growing use as the primary method of accessing the internet, mobile-first website design has become a top priority for businesses and organizations of all sizes. As a result, the demand for efficient, user-friendly, and effective frameworks for building mobile-first websites and applications has skyrocketed.
One of the most widely used and highly regarded frameworks for building mobile-first websites and applications is React. In this article, we will discuss the importance of React in building mobile-first websites and applications, its key features, and why it has become such a popular choice for developers.
What is React?
React is an open-source JavaScript library for building user interfaces. It was developed by Facebook in 2011 and has since been adopted by a large number of companies and organizations, including Airbnb, Netflix, and Dropbox. React was created to address the problems of building complex user interfaces, and it has since become one of the most popular JavaScript libraries for front-end development.
Why is React Important for Building Mobile-First Websites and Applications?
Key Features of React
Furthermore, React provides an intuitive and flexible programming model that makes it easy for developers to create complex and interactive user interfaces. The component-based architecture of React allows developers to break down user interfaces into smaller, reusable components, making it easier to manage and maintain complex applications.
One of the biggest advantages of React is its ability to efficiently update the user interface in real-time. With React developers can implement dynamic and responsive user interfaces that respond to changes in real-time, providing users with a smooth and seamless experience. This is particularly important in the context of mobile-first websites and applications, where users expect fast and responsive experiences on their mobile devices.
React also integrates well with other tools and technologies, making it easy for developers to build complex and feature-rich applications. For example, react can be used in conjunction with popular front-end frameworks such as Redux and MobX, as well as with back-end technologies like Node.js and GraphQL. This integration with other technologies makes it possible for developers to build complete and full-featured web applications using React.
Moreover, React also offers a high level of developer productivity, allowing developers to build applications faster and with fewer bugs. The React library includes many helpful tools and resources, such as the React Developer Tools browser extension, which makes it easier for developers to debug and optimize their applications. The large and active React community also provides a wealth of information and resources, including tutorials, code examples, and discussion forums, making it easier for developers to find the information they need to build high-quality applications.
Another advantage of React is its ability to handle large amounts of data and provide fast, responsive user interfaces. React uses a virtual DOM (Document Object Model) that allows it to efficiently update the user interface without having to re-render the entire page. This makes it possible to build fast and responsive user interfaces even when dealing with large amounts of data, which is essential for mobile-first applications where users expect fast and smooth experiences.
React is also a good choice for building cross-platform applications. With React, developers can build applications that run on multiple platforms, including web, iOS, and Android. This makes it a versatile and cost-effective solution for organizations that need to build applications that run on multiple platforms. Additionally, React Native, a framework for building native mobile applications using React, makes it possible for developers to build high-quality native mobile applications using the same codebase as their web applications.
Finally, React is SEO-friendly, making it a good choice for organizations that need to build mobile-first websites and applications that are optimized for search engines. React uses server-side rendering, which makes it possible for search engines to index and understand the content of a React-powered website. This is important for organizations that need to build websites that are optimized for search engines, as it helps to ensure that their website will rank higher in search engine results and reach more users.
Conclusion
In conclusion, React is an important framework for building mobile-first websites and applications. Its key features, such as its virtual DOM, components one-way data flow, and server-side rendering, make it a highly efficient and effective choice for developers. The large and active community of React developers also means that it is constantly evolving and improving, ensuring that it remains relevant and up-to-date with the latest trends and technologies.
In addition to its technical strengths, React has also proven to be a popular choice for businesses and organizations due to its ability to provide improved user experiences, faster development times, cross-platform compatibility, and SEO-friendliness. All of these factors make React a valuable asset for building mobile-first websites and applications.
As mobile devices continue to be the primary method of accessing the internet, the importance of React in building mobile-first websites and applications will only continue to grow. Businesses and organizations that prioritize mobile-first design will benefit from the many advantages that React has to offer and will be well-positioned to succeed in the increasingly mobile-centric world.
1656984600
今天,我继续分享我在 Native Module 和 C++ 方面的经验。
由于我们将看到很多为移动平台编写的 C/C++ 库,因此我们需要将它们实现到我们的 iOS 或 React Native 应用程序中。这就是为什么我想写一篇关于如何将一个函数从 C++ 导出到 React Native 的文章,它易于理解并且为初学者节省了时间。我将从一个新的 react native 应用程序开始
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) 端
一个。创建一个Objective C文件并命名Cpp_to_RN.m
重命名Cpp_to_RN.m
为 Cpp_to_RN.mm
湾。打开WrapCpp_to_RN.mm
文件并编写将包装sayHello
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。创建头文件并命名WrapCpp_to_RN.h
将函数导出wrapSayHello
到 Swift 文件
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
将 C++ 函数导出到 React Native
一个。创建一个 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()
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])
}}
湾。将 Swift 文件中的包装函数导出到 React Native
创建一个 Objective C 文件以导出 Swift 类及其函数,使用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 连接到 React Native,打开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 上的“运行”按钮,看看我们做了什么。
希望我的文章对您有所帮助,感谢您的阅读时间。
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.
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.
1656981000
Hôm nay, tôi tiếp tục chia sẻ kinh nghiệm của mình với Native Module và C ++.
Vì chúng ta sẽ thấy rất nhiều thư viện C / C ++ viết cho nền tảng di động, chúng ta cần triển khai chúng cho ứng dụng iOS hoặc React Native của mình. Đó là lý do mình muốn viết một bài hướng dẫn cách export một hàm từ C ++ sang React Native dễ hiểu và tiết kiệm thời gian cho người mới bắt đầu. Tôi sẽ bắt đầu với một ứng dụng gốc phản ứng mới
npx react-native init NativeModules
Tạo một tệp C ++ mới và đặt tên cho nóCpp_to_RN.cpp
Khi chúng tôi tạo tệp C ++ mới, Xcode sẽ tạo tệp tiêu đề Cpp_to_RN.hpp
cho chúng tôi
Đầu tiên, mở tệp Cpp_to_RN.hpp
“” và tạo một lớp bao gồm một hàm không có phần thân.
#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 */
Sau đó, mở Cpp_to_RN.cpp
tệp và viết một hàm đơn giản “ sayHello()
”
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
Để bọc các tệp C ++ và xuất chúng sang phía IOS (nhanh chóng)
một. Tạo một tệp Objective C và đặt tên cho nóCpp_to_RN.m
Đổi tên Cpp_to_RN.m
thành Cpp_to_RN.mm
b. Mở WrapCpp_to_RN.mm
tệp và viết nội dung phần nội dung sẽ bọc hàm sayHello
từ tệp 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. Tạo một tệp tiêu đề và đặt tên cho nóWrapCpp_to_RN.h
Xuất wrapSayHello
hàm sang tệp Swift
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Để xuất hàm C ++ sang React Native
một. Tạo một tệp Swift và đặt tên cho nóSendCpp_to_RN.swift
Lưu ý: Xcode sẽ yêu cầu chúng tôi tạo một NativeModules-Bridging-Header.h
tệp cho chúng tôi.
Tạo một lớp SendCpp_to_RN
và khai báo nó làNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Viết một hàm requiresMainQueueSetup()
để ngăn cảnh báo khi chúng tôi chạy ứng dụng
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Viết một hàm để bọc WrapCpp_to_RN()
từ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. Xuất một hàm bọc trong tệp Swift sang React Native
Tạo một tệp Objective C để xuất lớp Swift và chức năng của nó bằng cách sử dụngCallback
#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. Kết nối Swift với React Native, mở NativeModules-Bridging-Header.h
tệp
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Gọi lớp Swift và các chức năng của nó
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;
Và chúng tôi đã hoàn tất, chỉ cần chạy ứng dụng
react-native run-ios
Hoặc chỉ cần nhấp vào nút “chạy” trên Xcode và xem những gì chúng tôi đã làm.
Tôi hy vọng bài viết của tôi hữu ích cho bạn, cảm ơn bạn đã dành thời gian đọc.
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.