การเขียนโมดูลเนทีฟแบบเดิมใน Kotlin
สร้าง ReactContextBaseJavaModule ใน Kotlin ใส่คำอธิบายกำกับเมธอดด้วย @ReactMethod เปิดเผยผ่าน ReactPackage และเรียกใช้จาก JavaScript
การเขียนโมดูลเนทีฟแบบเดิมใน Kotlin เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is a Legacy Native Module
A legacy native module allows you to call native Android (Kotlin/Java) code from JavaScript in a React Native app. When the built-in React Native APIs do not cover a device feature you need, you write a native module to bridge the gap. Legacy modules use the Bridge architecture, which means calls go asynchronously across the JS-to-native bridge.
Creating the Kotlin Module Class
Every Android native module extends ReactContextBaseJavaModule. You override getName() to return the name that JavaScript will use to call your module. Place this class inside the android/app/src/main/java/com/yourapp/ folder alongside existing Android source files.
// ToastModule.kt
package com.yourapp
import android.widget.Toast
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
class ToastModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
override fun getName(): String = 'ToastModule'
}Annotating Methods with @ReactMethod
Any method you want to expose to JavaScript must be annotated with @ReactMethod. The method must be public and its return type must be void — results are returned asynchronously via callbacks or promises, not return values. React Native serializes parameters automatically for basic types like String, Int, Boolean, and Double.
@ReactMethod
fun show(message: String, duration: Int) {
val durationConst = if (duration == Toast.LENGTH_SHORT)
Toast.LENGTH_SHORT else Toast.LENGTH_LONG
Toast.makeText(reactApplicationContext, message, durationConst).show()
}Creating the ReactPackage
Native modules must be registered through a ReactPackage. You implement the ReactPackage interface and return your module from createNativeModules. The package is then added to the list of packages in MainApplication.kt so React Native includes it at startup.
// ToastPackage.kt
package com.yourapp
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class ToastPackage : ReactPackage {
override fun createNativeModules(
reactContext: ReactApplicationContext
): List<NativeModule> = listOf(ToastModule(reactContext))
override fun createViewManagers(
reactContext: ReactApplicationContext
): List<ViewManager<*, *>> = emptyList()
}Registering the Package in MainApplication
Open MainApplication.kt and find the getPackages() method. Add an instance of your ToastPackage to the list. React Native calls this during startup to discover all available native modules and register their JavaScript interfaces.
// MainApplication.kt (inside getPackages)
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
add(ToastPackage()) // <-- register your package here
}Calling the Module from JavaScript
On the JavaScript side, import NativeModules from react-native and access your module by the name returned from getName(). Wrap the native module in a helper file to provide a clean TypeScript API and hide the raw NativeModules reference from your components.
// ToastModule.js
import { NativeModules } from 'react-native';
const { ToastModule } = NativeModules;
export function showToast(message, duration = 'short') {
const dur = duration === 'short' ? 0 : 1;
ToastModule.show(message, dur);
}
// Usage in a component:
// import { showToast } from './ToastModule';
// showToast('Hello from native!', 'long');Returning Values with Promises
Because @ReactMethod methods must return void, you use Promise parameters to send data back to JavaScript. Add promise: Promise as the last parameter, call promise.resolve(value) on success, or promise.reject(code, message) on error. On the JS side you await the call like any async function.
// Kotlin
@ReactMethod
fun getDeviceName(promise: Promise) {
try {
val name = android.os.Build.MODEL
promise.resolve(name)
} catch (e: Exception) {
promise.reject('ERROR', e.message)
}
}
// JavaScript
const name = await NativeModules.MyModule.getDeviceName();
console.log('Device:', name);Using Callbacks as an Alternative
Before Promises became standard, native modules used Callback parameters (Callback type in the SDK). You receive one or two callbacks — typically successCallback and errorCallback — and invoke them from native code. Callbacks can only be called once; use Promises or events for repeated responses.
@ReactMethod
fun getBatteryLevel(
successCallback: Callback,
errorCallback: Callback
) {
try {
val intent = reactApplicationContext.registerReceiver(
null,
android.content.IntentFilter(
android.content.Intent.ACTION_BATTERY_CHANGED
)
)
val level = intent?.getIntExtra(
android.os.BatteryManager.EXTRA_LEVEL, -1
) ?: -1
successCallback.invoke(level)
} catch (e: Exception) {
errorCallback.invoke(e.message)
}
}Passing Complex Data with WritableMap
To return an object (JSON map) from native to JavaScript, use WritableMap and Arguments.createMap(). You add key-value pairs to the map using typed putters like putString, putInt, and putBoolean. The map is automatically serialized into a JavaScript object when it reaches the JS layer.
@ReactMethod
fun getDeviceInfo(promise: Promise) {
val map = Arguments.createMap()
map.putString('model', android.os.Build.MODEL)
map.putString('brand', android.os.Build.BRAND)
map.putInt('sdkVersion', android.os.Build.VERSION.SDK_INT)
map.putBoolean('isTablet', reactApplicationContext
.resources.configuration.smallestScreenWidthDp >= 600)
promise.resolve(map)
}The isBlockingSynchronousMethod Annotation
By default all @ReactMethod calls are asynchronous. Adding isBlockingSynchronousMethod = true makes the call synchronous — the JS thread blocks until native returns. This is strongly discouraged in production because it freezes the UI, but it can be useful for debugging or reading a tiny cached value that must be available immediately.
@ReactMethod(isBlockingSynchronousMethod = true)
fun getAppVersionSync(): String {
return reactApplicationContext
.packageManager
.getPackageInfo(reactApplicationContext.packageName, 0)
.versionName ?: 'unknown'
}Module Constants via getConstants
You can expose compile-time constants to JavaScript by overriding getConstants() in your module. Constants are transferred once at startup and are synchronously accessible as NativeModules.MyModule.CONSTANT_NAME with no async call needed. Use constants for fixed values like error codes, config flags, or platform identifiers.
override fun getConstants(): Map<String, Any> {
return mapOf(
'LONG_TOAST' to Toast.LENGTH_LONG,
'SHORT_TOAST' to Toast.LENGTH_SHORT,
'PLATFORM' to 'android'
)
}
// In JavaScript:
// const { LONG_TOAST } = NativeModules.ToastModule;
// showToast('Hello!', LONG_TOAST);Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: how to create a ReactContextBaseJavaModule in Kotlin, annotate methods with @ReactMethod to expose them to JavaScript, and register the module through a ReactPackage in MainApplication. You also saw how to return data using Promises and WritableMap. Next up we explore writing a legacy native module in Swift for iOS.
คำถามที่พบบ่อย
บทเรียน “การเขียนโมดูลเนทีฟแบบเดิมใน Kotlin” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การเขียนโมดูลเนทีฟแบบเดิมใน Kotlin” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การเขียนโมดูลเนทีฟแบบเดิมใน Kotlin”
สร้าง ReactContextBaseJavaModule ใน Kotlin ใส่คำอธิบายกำกับเมธอดด้วย @ReactMethod เปิดเผยผ่าน ReactPackage และเรียกใช้จาก JavaScript คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การเขียนโมดูลเนทีฟแบบเดิมใน Kotlin” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเขียนโมดูลเนทีฟแบบเดิมใน Kotlin
- การเขียนโมดูลเนทีฟแบบเดิมใน Swift
- โมดูลเนทีฟ Turbo ด้วย JSI
- ตัวเรียกกลับแบบอะซิงโครนัส พรอมิส และเหตุการณ์จากเนทีฟ