네이티브 컴포넌트
호스트 컴포넌트를 감싸는 새로운 React Native 컴포넌트를 만들고 싶다면, 예를 들어 안드로이드의 CheckBox나 iOS의 UIButton과 같은 고유한 컴포넌트를 만들고자 한다면, Fabric 네이티브 컴포넌트를 사용해야 한다.
이 가이드는 웹 뷰 컴포넌트를 구현하면서 Fabric 네이티브 컴포넌트를 만드는 방법을 보여준다. 이를 위한 단계는 다음과 같다:
- Flow나 TypeScript를 사용해 JavaScript 스펙을 정의한다.
- 제공된 스펙에서 코드를 생성하고 자동 연결되도록 의존성 관리 시스템을 설정한다.
- 네이티브 코드를 구현한다.
- 앱에서 컴포넌트를 사용한다.
컴포넌트를 사용하기 위해 일반 템플릿으로 생성된 애플리케이션이 필요하다:
npx @react-native-community/cli@latest init Demo --install-pods false
WebView 컴포넌트 만들기
이 가이드에서는 WebView 컴포넌트를 만드는 방법을 설명한다. Android의 WebView
컴포넌트와 iOS의 WKWebView
컴포넌트를 사용해 컴포넌트를 만들 것이다.
먼저 컴포넌트 코드를 담을 폴더 구조를 만든다:
mkdir -p Demo/{specs,android/app/src/main/java/com/webview}
이 명령어를 실행하면 다음과 같은 구조가 만들어진다:
Demo
├── android/app/src/main/java/com/webview
└── ios
└── specs
android/app/src/main/java/com/webview
폴더는 Android 코드를 담을 폴더이다.ios
폴더는 iOS 코드를 담을 폴더이다.specs
폴더는 Codegen의 스펙 파일을 담을 폴더이다.
1. 코드 생성 명세서 정의
코드 생성 명세서는 TypeScript나 Flow로 정의해야 한다. (자세한 내용은 코드 생성 문서를 참고한다.) 이 명세서는 Codegen이 C++, Objective-C++, Java 코드를 생성해 플랫폼 코드와 React가 실행되는 JavaScript 런타임을 연결하는 데 사용된다.
명세서 파일은 Codegen이 인식할 수 있도록 <MODULE_NAME>NativeComponent.{ts|js}
형식으로 이름을 지어야 한다. NativeComponent
접미사는 단순한 관례가 아니라 Codegen이 명세서 파일을 식별하는 데 실제로 사용된다.
다음은 WebView 컴포넌트를 위한 명세서 예제다:
- TypeScript
- Flow
import type {HostComponent, ViewProps} from 'react-native';
import type {BubblingEventHandler} from 'react-native/Libraries/Types/CodegenTypes';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
type WebViewScriptLoadedEvent = {
result: 'success' | 'error';
};
export interface NativeProps extends ViewProps {
sourceURL?: string;
onScriptLoaded?: BubblingEventHandler<WebViewScriptLoadedEvent> | null;
}
export default codegenNativeComponent<NativeProps>(
'CustomWebView',
) as HostComponent<NativeProps>;
// @flow strict-local
import type {HostComponent, ViewProps} from 'react-native';
import type {BubblingEventHandler} from 'react-native/Libraries/Types/CodegenTypes';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
type WebViewScriptLoadedEvent = $ReadOnly<{|
result: "success" | "error",
|}>;
type NativeProps = $ReadOnly<{|
...ViewProps,
sourceURL?: string;
onScriptLoaded?: BubblingEventHandler<WebViewScriptLoadedEvent>?;
|}>;
export default (codegenNativeComponent<NativeProps>(
'CustomWebView',
): HostComponent<NativeProps>);
이 명세서는 import 문을 제외하고 세 가지 주요 부분으로 구성된다:
WebViewScriptLoadedEvent
는 네이티브에서 JavaScript로 전달해야 하는 이벤트 데이터를 위한 지원 데이터 타입이다.NativeProps
는 컴포넌트에 설정할 수 있는 props를 정의한다.codegenNativeComponent
문은 커스텀 컴포넌트를 위한 코드를 생성하며, 네이티브 구현과 매칭할 컴포넌트 이름을 정의한다.
네이티브 모듈과 마찬가지로, specs/
디렉토리에 여러 명세서 파일을 둘 수 있다. 사용할 수 있는 타입과 이들이 매핑되는 플랫폼 타입에 대한 자세한 내용은 부록을 참고한다.
2. Codegen 실행 설정
React Native의 Codegen 도구는 플랫폼별 인터페이스와 보일러플레이트 코드를 자동으로 생성하기 위해 스펙을 사용한다. 이를 위해 Codegen은 스펙 파일의 위치와 이를 어떻게 처리할지 알아야 한다. package.json
파일을 다음과 같이 업데이트한다:
"start": "react-native start",
"test": "jest"
},
"codegenConfig": {
"name": "AppSpec",
"type": "components",
"jsSrcsDir": "specs",
"android": {
"javaPackageName": "com.webview"
},
"ios": {
"componentProvider": {
"CustomWebView": "RCTWebView"
}
}
},
"dependencies": {
Codegen을 위한 모든 설정이 완료되면, 네이티브 코드가 생성된 코드와 연결되도록 준비해야 한다.
iOS의 경우, 스펙에서 내보내는 JS 컴포넌트의 이름(CustomWebView
)을 네이티브로 구현할 iOS 클래스와 명시적으로 매핑한다.
2. 네이티브 코드 작성하기
이제 React가 뷰를 렌더링할 때 플랫폼이 올바른 네이티브 뷰를 생성하고 화면에 렌더링할 수 있도록 네이티브 플랫폼 코드를 작성할 차례다.
Android와 iOS 두 플랫폼 모두에 대해 작업을 진행해야 한다.
이 가이드는 새로운 아키텍처(New Architecture)에서만 동작하는 네이티브 컴포넌트를 만드는 방법을 보여준다. 새로운 아키텍처와 레거시 아키텍처(Legacy Architecture) 모두를 지원해야 하는 경우, 하위 호환성 가이드를 참고한다.
- Android
- iOS
이제 웹 뷰를 렌더링할 수 있도록 안드로이드 플랫폼 코드를 작성할 차례다. 따라야 할 단계는 다음과 같다:
- Codegen 실행
ReactWebView
코드 작성ReactWebViewManager
코드 작성ReactWebViewPackage
코드 작성- 애플리케이션에서
ReactWebViewPackage
등록
1. Gradle을 통해 Codegen 실행하기
한 번 실행하면 여러분이 선택한 IDE에서 사용할 수 있는 보일러플레이트 코드를 생성한다.
cd android
./gradlew generateCodegenArtifactsFromSchema
Codegen은 구현해야 할 ViewManager
인터페이스와 웹 뷰를 위한 ViewManager
델리게이트를 생성한다.
2. ReactWebView
작성하기
ReactWebView
는 React Native가 커스텀 컴포넌트를 사용할 때 렌더링하는 Android 네이티브 뷰를 감싸는 컴포넌트이다.
android/src/main/java/com/webview
폴더에 ReactWebView.java
또는 ReactWebView.kt
파일을 생성하고 아래 코드를 추가한다:
- Java
- Kotlin
package com.webview;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.uimanager.UIManagerHelper;
import com.facebook.react.uimanager.events.Event;
public class ReactWebView extends WebView {
public ReactWebView(Context context) {
super(context);
configureComponent();
}
public ReactWebView(Context context, AttributeSet attrs) {
super(context, attrs);
configureComponent();
}
public ReactWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
configureComponent();
}
private void configureComponent() {
this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
this.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
emitOnScriptLoaded(OnScriptLoadedEventResult.success);
}
});
}
public void emitOnScriptLoaded(OnScriptLoadedEventResult result) {
ReactContext reactContext = (ReactContext) context;
int surfaceId = UIManagerHelper.getSurfaceId(reactContext);
EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());
WritableMap payload = Arguments.createMap();
payload.putString("result", result.name());
OnScriptLoadedEvent event = new OnScriptLoadedEvent(surfaceId, getId(), payload);
if (eventDispatcher != null) {
eventDispatcher.dispatchEvent(event);
}
}
public enum OnScriptLoadedEventResult {
success,
error
}
private class OnScriptLoadedEvent extends Event<OnScriptLoadedEvent> {
private final WritableMap payload;
OnScriptLoadedEvent(int surfaceId, int viewId, WritableMap payload) {
super(surfaceId, viewId);
this.payload = payload;
}
@Override
public String getEventName() {
return "onScriptLoaded";
}
@Override
public WritableMap getEventData() {
return payload;
}
}
}
package com.webview
import android.content.Context
import android.util.AttributeSet
import android.webkit.WebView
import android.webkit.WebViewClient
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableMap
import com.facebook.react.bridge.ReactContext
import com.facebook.react.uimanager.UIManagerHelper
import com.facebook.react.uimanager.events.Event
class ReactWebView: WebView {
constructor(context: Context) : super(context) {
configureComponent()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
configureComponent()
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
configureComponent()
}
private fun configureComponent() {
this.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
this.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
emitOnScriptLoaded(OnScriptLoadedEventResult.success)
}
}
}
fun emitOnScriptLoaded(result: OnScriptLoadedEventResult) {
val reactContext = context as ReactContext
val surfaceId = UIManagerHelper.getSurfaceId(reactContext)
val eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id)
val payload =
Arguments.createMap().apply {
putString("result", result.name)
}
val event = OnScriptLoadedEvent(surfaceId, id, payload)
eventDispatcher?.dispatchEvent(event)
}
enum class OnScriptLoadedEventResult {
success,
error;
}
inner class OnScriptLoadedEvent(
surfaceId: Int,
viewId: Int,
private val payload: WritableMap
) : Event<OnScriptLoadedEvent>(surfaceId, viewId) {
override fun getEventName() = "onScriptLoaded"
override fun getEventData() = payload
}
}
ReactWebView
는 Android의 WebView
를 확장하여 플랫폼에서 이미 정의된 모든 속성을 쉽게 재사용할 수 있다.
이 클래스는 Android의 세 가지 생성자를 정의하지만, 실제 구현은 configureComponent
라는 private 함수로 위임한다. 이 함수는 컴포넌트의 특정 속성을 초기화하는 역할을 한다. 여기서는 WebView
의 레이아웃을 설정하고, WebView
의 동작을 커스텀하기 위해 WebClient
를 정의한다. 이 코드에서 ReactWebView
는 페이지 로딩이 완료될 때 이벤트를 발생시키는데, 이는 WebClient
의 onPageFinished
메서드를 구현함으로써 가능하다.
그 다음, 실제로 이벤트를 발생시키는 헬퍼 함수를 정의한다. 이벤트를 발생시키려면 다음과 같은 단계를 거쳐야 한다:
ReactContext
의 참조를 가져온다.- 현재 표시 중인 뷰의
surfaceId
를 가져온다. - 뷰와 연결된
eventDispatcher
의 참조를 가져온다. WritableMap
객체를 사용해 이벤트의 페이로드를 생성한다.- JavaScript로 보낼 이벤트 객체를 생성한다.
eventDispatcher.dispatchEvent
를 호출해 이벤트를 전송한다.
파일의 마지막 부분에는 이벤트 전송에 필요한 데이터 타입을 정의한다:
OnScriptLoadedEventResult
:OnScriptLoaded
이벤트의 가능한 결과를 나타낸다.OnScriptLoadedEvent
: React Native의Event
클래스를 확장해야 하는 실제 이벤트이다.
3. WebViewManager
작성하기
WebViewManager
는 React Native 런타임과 네이티브 뷰를 연결하는 클래스이다.
앱에서 특정 컴포넌트를 렌더링하라는 지시를 받으면, React는 등록된 뷰 매니저를 사용해 뷰를 생성하고 필요한 모든 속성을 전달한다.
다음은 ReactWebViewManager
의 코드이다.
- Java
- Kotlin
package com.webview;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewManagerDelegate;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;
import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;
import java.util.HashMap;
import java.util.Map;
@ReactModule(name = ReactWebViewManager.REACT_CLASS)
class ReactWebViewManager extends SimpleViewManager<ReactWebView> implements CustomWebViewManagerInterface<ReactWebView> {
private final CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> delegate =
new CustomWebViewManagerDelegate<>(this);
@Override
public ViewManagerDelegate<ReactWebView> getDelegate() {
return delegate;
}
@Override
public String getName() {
return REACT_CLASS;
}
@Override
public ReactWebView createViewInstance(ThemedReactContext context) {
return new ReactWebView(context);
}
@ReactProp(name = "sourceUrl")
@Override
public void setSourceURL(ReactWebView view, String sourceURL) {
if (sourceURL == null) {
view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error);
return;
}
view.loadUrl(sourceURL, new HashMap<>());
}
public static final String REACT_CLASS = "CustomWebView";
@Override
public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
Map<String, Object> map = new HashMap<>();
Map<String, Object> bubblingMap = new HashMap<>();
bubblingMap.put("phasedRegistrationNames", new HashMap<String, String>() {{
put("bubbled", "onScriptLoaded");
put("captured", "onScriptLoadedCapture");
}});
map.put("onScriptLoaded", bubblingMap);
return map;
}
}
package com.webview
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewManagerDelegate;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;
import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;
@ReactModule(name = ReactWebViewManager.REACT_CLASS)
class ReactWebViewManager(context: ReactApplicationContext) : SimpleViewManager<ReactWebView>(), CustomWebViewManagerInterface<ReactWebView> {
private val delegate: CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> =
CustomWebViewManagerDelegate(this)
override fun getDelegate(): ViewManagerDelegate<ReactWebView> = delegate
override fun getName(): String = REACT_CLASS
override fun createViewInstance(context: ThemedReactContext): ReactWebView = ReactWebView(context)
@ReactProp(name = "sourceUrl")
override fun setSourceURL(view: ReactWebView, sourceURL: String?) {
if (sourceURL == null) {
view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error)
return;
}
view.loadUrl(sourceURL, emptyMap())
}
companion object {
const val REACT_CLASS = "CustomWebView"
}
override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> =
mapOf(
"onScriptLoaded" to
mapOf(
"phasedRegistrationNames" to
mapOf(
"bubbled" to "onScriptLoaded",
"captured" to "onScriptLoadedCapture"
)))
}
ReactWebViewManager
는 React의 SimpleViewManager
클래스를 상속하고, Codegen에 의해 생성된 CustomWebViewManagerInterface
를 구현한다.
또한 Codegen에 의해 생성된 CustomWebViewManagerDelegate
의 참조를 가지고 있다.
getName
함수를 오버라이드하여, spec의 codegenNativeComponent
함수 호출에서 사용한 이름과 동일한 값을 반환한다.
createViewInstance
함수는 새로운 ReactWebView
를 인스턴스화하는 역할을 한다.
그런 다음, 뷰 매니저는 React 컴포넌트의 속성이 네이티브 뷰를 어떻게 업데이트할지 정의해야 한다. 예제에서는 React가 WebView
에 설정할 sourceURL
속성을 어떻게 처리할지 결정해야 한다.
마지막으로, 컴포넌트가 이벤트를 발생시킬 수 있다면, 버블링 이벤트를 위해 getExportedCustomBubblingEventTypeConstants
를 오버라이드하거나, 직접 이벤트를 위해 getExportedCustomDirectEventTypeConstants
를 오버라이드해 이벤트 이름을 매핑해야 한다.
4. ReactWebViewPackage
작성하기
네이티브 모듈과 마찬가지로, 네이티브 컴포넌트도 ReactPackage
클래스를 구현해야 한다. 이 클래스는 React Native 런타임에 컴포넌트를 등록하는 데 사용된다.
다음은 ReactWebViewPackage
의 코드이다:
- Java
- Kotlin
package com.webview;
import com.facebook.react.BaseReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.uimanager.ViewManager;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReactWebViewPackage extends BaseReactPackage {
@Override
public List<ViewManager<?, ?>> createViewManagers(ReactApplicationContext reactContext) {
return Collections.singletonList(new ReactWebViewManager(reactContext));
}
@Override
public NativeModule getModule(String s, ReactApplicationContext reactApplicationContext) {
if (ReactWebViewManager.REACT_CLASS.equals(s)) {
return new ReactWebViewManager(reactApplicationContext);
}
return null;
}
@Override
public ReactModuleInfoProvider getReactModuleInfoProvider() {
return new ReactModuleInfoProvider() {
@Override
public Map<String, ReactModuleInfo> get() {
Map<String, ReactModuleInfo> map = new HashMap<>();
map.put(ReactWebViewManager.REACT_CLASS, new ReactModuleInfo(
ReactWebViewManager.REACT_CLASS, // name
ReactWebViewManager.REACT_CLASS, // className
false, // canOverrideExistingModule
false, // needsEagerInit
false, // isCxxModule
true // isTurboModule
));
return map;
}
};
}
}
package com.webview
import com.facebook.react.BaseReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.module.model.ReactModuleInfo
import com.facebook.react.module.model.ReactModuleInfoProvider
import com.facebook.react.uimanager.ViewManager
class ReactWebViewPackage : BaseReactPackage() {
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return listOf(ReactWebViewManager(reactContext))
}
override fun getModule(s: String, reactApplicationContext: ReactApplicationContext): NativeModule? {
when (s) {
ReactWebViewManager.REACT_CLASS -> ReactWebViewManager(reactApplicationContext)
}
return null
}
override fun getReactModuleInfoProvider(): ReactModuleInfoProvider = ReactModuleInfoProvider {
mapOf(ReactWebViewManager.REACT_CLASS to ReactModuleInfo(
_name = ReactWebViewManager.REACT_CLASS,
_className = ReactWebViewManager.REACT_CLASS,
_canOverrideExistingModule = false,
_needsEagerInit = false,
isCxxModule = false,
isTurboModule = true,
)
)
}
}
ReactWebViewPackage
는 BaseReactPackage
를 상속받고, 컴포넌트를 올바르게 등록하기 위해 필요한 모든 메서드를 구현한다.
createViewManagers
메서드는 커스텀 뷰를 관리하는ViewManager
를 생성하는 팩토리 메서드이다.getModule
메서드는 React Native가 렌더링해야 하는 뷰에 따라 적절한ViewManager
를 반환한다.getReactModuleInfoProvider
는 런타임에 모듈을 등록할 때 필요한 모든 정보를 제공한다.
5. ReactWebViewPackage
를 애플리케이션에 등록하기
마지막으로, ReactWebViewPackage
를 애플리케이션에 등록해야 한다. 이를 위해 MainApplication
파일을 수정하여 getPackages
함수가 반환하는 패키지 목록에 ReactWebViewPackage
를 추가한다.
package com.demo
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.soloader.SoLoader
import com.webview.ReactWebViewPackage
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
add(ReactWebViewPackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, OpenSourceMergedSoMapping)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
load()
}
}
}
이제 웹 뷰를 렌더링할 수 있도록 iOS 플랫폼 코드를 작성할 차례이다. 따라야 할 단계는 다음과 같다:
- Codegen을 실행한다.
RCTWebView
에 대한 코드를 작성한다.- 애플리케이션에
RCTWebView
를 등록한다.
1. 코드 생성 실행하기
코드 생성을 수동으로 실행할 수 있지만, 컴포넌트를 데모할 애플리케이션을 사용해 자동으로 실행하는 것이 더 간단하다.
cd ios
bundle install
bundle exec pod install
중요한 점은 코드 생성 과정에서 출력되는 로그를 확인할 수 있다는 것이다. 이 로그는 Xcode에서 WebView 네이티브 컴포넌트를 빌드할 때 사용할 예정이다.
생성된 코드를 저장소에 커밋할 때 주의해야 한다. 생성된 코드는 React Native의 각 버전에 따라 다르다. npm의 peerDependencies를 사용해 React Native 버전과의 호환성을 제한해야 한다.
3. RCTWebView
작성하기
Xcode를 사용해 iOS 프로젝트를 준비하려면 다음 5단계를 완료해야 한다.
- CocoPods로 생성된 Xcode Workspace를 연다:
cd ios
open Demo.xcworkspace

- 앱을 우클릭하고
New Group
을 선택한 후, 새로운 그룹 이름을WebView
로 지정한다.

WebView
그룹 안에서New
→File from Template
을 생성한다.

Objective-C File
템플릿을 사용하고, 파일 이름을RCTWebView
로 지정한다.

-
4단계를 반복해
RCTWebView.h
라는 헤더 파일을 생성한다. -
RCTWebView.m
파일을RCTWebView.mm
으로 변경해 Objective-C++ 파일로 만든다.
Podfile
...
Demo
├── AppDelegate.swift
...
├── RCTWebView.h
└── RCTWebView.mm
헤더 파일과 구현 파일을 생성한 후, 이제 구현을 시작할 수 있다.
RCTWebView.h
파일의 코드는 컴포넌트 인터페이스를 선언한다.
#import <React/RCTViewComponentView.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface RCTWebView : RCTViewComponentView
// 뷰에서 접근할 네이티브 메서드를 여기에 선언한다.
@end
NS_ASSUME_NONNULL_END
이 클래스는 RCTViewComponentView
클래스를 확장한 RCTWebView
를 정의한다. 이 클래스는 모든 네이티브 컴포넌트의 기본 클래스이며, React Native에서 제공한다.
구현 파일(RCTWebView.mm
)의 코드는 다음과 같다:
#import "RCTWebView.h"
#import <react/renderer/components/AppSpec/ComponentDescriptors.h>
#import <react/renderer/components/AppSpec/EventEmitters.h>
#import <react/renderer/components/AppSpec/Props.h>
#import <react/renderer/components/AppSpec/RCTComponentViewHelpers.h>
#import <WebKit/WebKit.h>
using namespace facebook::react;
@interface RCTWebView () <RCTCustomWebViewViewProtocol, WKNavigationDelegate>
@end
@implementation RCTWebView {
NSURL * _sourceURL;
WKWebView * _webView;
}
-(instancetype)init
{
if(self = [super init]) {
_webView = [WKWebView new];
_webView.navigationDelegate = self;
[self addSubview:_webView];
}
return self;
}
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &oldViewProps = *std::static_pointer_cast<CustomWebViewProps const>(_props);
const auto &newViewProps = *std::static_pointer_cast<CustomWebViewProps const>(props);
// props를 처리한다.
if (oldViewProps.sourceURL != newViewProps.sourceURL) {
NSString *urlString = [NSString stringWithCString:newViewProps.sourceURL.c_str() encoding:NSUTF8StringEncoding];
_sourceURL = [NSURL URLWithString:urlString];
if ([self urlIsValid:newViewProps.sourceURL]) {
[_webView loadRequest:[NSURLRequest requestWithURL:_sourceURL]];
}
}
[super updateProps:props oldProps:oldProps];
}
-(void)layoutSubviews
{
[super layoutSubviews];
_webView.frame = self.bounds;
}
#pragma mark - WKNavigationDelegate
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Success};
self.eventEmitter.onScriptLoaded(result);
}
- (BOOL)urlIsValid:(std::string)propString
{
if (propString.length() > 0 && !_sourceURL) {
CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Error};
self.eventEmitter.onScriptLoaded(result);
return NO;
}
return YES;
}
// 이벤트 에미터 편의 메서드
- (const CustomWebViewEventEmitter &)eventEmitter
{
return static_cast<const CustomWebViewEventEmitter &>(*_eventEmitter);
}
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<CustomWebViewComponentDescriptor>();
}
@end
이 코드는 Objective-C++로 작성되었으며, 다양한 세부 사항을 포함한다:
@interface
는 두 프로토콜을 구현한다:- Codegen에 의해 생성된
RCTCustomWebViewViewProtocol
; - WebKit 프레임워크에서 제공하는
WKNavigationDelegate
로, 웹 뷰 네비게이션 이벤트를 처리한다;
- Codegen에 의해 생성된
init
메서드는WKWebView
를 인스턴스화하고, 서브뷰로 추가하며,navigationDelegate
를 설정한다;updateProps
메서드는 컴포넌트의 props가 변경될 때 React Native에 의해 호출된다;layoutSubviews
메서드는 커스텀 뷰의 레이아웃 방식을 정의한다;webView:didFinishNavigation:
메서드는WKWebView
가 페이지 로딩을 완료했을 때의 동작을 처리한다;urlIsValid:(std::string)propString
메서드는 prop으로 받은 URL이 유효한지 확인한다;eventEmitter
메서드는 강력한 타입의eventEmitter
인스턴스를 얻기 위한 유틸리티 메서드다;componentDescriptorProvider
는 Codegen에 의해 생성된ComponentDescriptor
를 반환한다;
WebKit 프레임워크 추가
이 단계는 웹 뷰를 생성할 때만 필요하다. iOS의 웹 컴포넌트는 Apple이 제공하는 WebKit 프레임워크와 연결되어야 한다. 컴포넌트가 웹 관련 기능을 사용하지 않는다면 이 단계를 건너뛰어도 된다.
웹 뷰는 Xcode와 디바이스에 포함된 프레임워크 중 하나인 WebKit을 통해 Apple이 제공하는 일부 기능에 접근해야 한다. 네이티브 코드에서는 RCTWebView.mm
에 추가된 #import <WebKit/WebKit.h>
라인을 통해 이를 확인할 수 있다.
앱에 WebKit 프레임워크를 연결하려면 다음 단계를 따르면 된다:
- Xcode에서 프로젝트를 클릭한다.
- 앱 타겟을 선택한다.
- General 탭을 선택한다.
- "Frameworks, Libraries, and Embedded Contents" 섹션을 찾을 때까지 스크롤하고,
+
버튼을 누른다.

- 검색창에서 WebKit을 필터링한다.
- WebKit 프레임워크를 선택한다.
- Add를 클릭한다.

커스텀 iOS 컴포넌트로 앱을 빌드할 때 발생할 수 있는 몇 가지 문제가 있다.
- 컴포넌트가
yoga/style/Style.h
헤더에 접근해야 하는데, 현재 앱에서 이 헤더를 사용할 수 없다. 이 문제를 해결하려면 앱의 헤더 검색 경로 빌드 설정에$(PODS_ROOT)/Headers/Private/Yoga
경로를 추가하면 된다. - Codegen이
RCTThirdPartyFabricComponentsProvider
에 생성해서는 안 되는 라인을 생성하고 있다.RCTThirdPartyFabricComponentsProvider.h
와RCTThirdPartyFabricComponentsProvider.mm
파일에서WebViewCls
심볼이 있는 라인을 제거하면 된다.
이 문제는 이미 수정되었으며 React Native 0.76.2 버전에서 반영될 예정이다.
3. 네이티브 컴포넌트 사용하기
마지막으로, 새로 만든 컴포넌트를 앱에서 사용할 수 있다. 생성된 App.tsx
파일을 다음과 같이 업데이트한다:
import React from 'react';
import {Alert, StyleSheet, View} from 'react-native';
import WebView from './specs/WebViewNativeComponent';
function App(): React.JSX.Element {
return (
<View style={styles.container}>
<WebView
sourceURL="https://react.dev/"
style={styles.webview}
onScriptLoaded={() => {
Alert.alert('Page Loaded');
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
alignContent: 'center',
},
webview: {
width: '100%',
height: '100%',
},
});
export default App;
이 코드는 react.dev
웹사이트를 로드하기 위해 우리가 만든 새로운 WebView
컴포넌트를 사용하는 앱을 만든다.
웹 페이지가 로드되면 앱에서 알림을 표시한다.
4. WebView 컴포넌트를 사용해 앱 실행하기
- Android
- iOS
yarn run android
yarn run ios
Android | iOS |
---|---|
![]() | ![]() |