1.android端集成SimpleViewManager<這里寫組件的名字也可以是自定義過的組件>
2.復(fù)寫createViewInstance通過這個方法來返回需要使用的原生的view
@Override
protected Button createViewInstance(ThemedReactContext reactContext) {
this.mContext = reactContext;
Button button = new Button(reactContext);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
WritableMap map = Arguments.createMap();
map.putString("msg","我是來自原生view的點擊顯示");
ReactContext context = (ReactContext)button.getContext();
context.getJSModule(RCTEventEmitter.class).receiveEvent(textView.getId(),"myclicked",map);
}
});
return button;
}
3.使用@ReactProp導(dǎo)出的是js設(shè)置的屬性
@ReactProp(name = "msg")
public void setText(Button button,String text){
button.setText(text);
}
4.在android原生端定義了使用的屬性還需要定義一個類實現(xiàn)ReactPackage
//自定義RTCViewPackage
public classRTCViewPackage implements ReactPackage{
@OverridepublicListcreateNativeModules(ReactApplicationContext reactContext){returnCollections.EMPTY_LIST; } @OverridepublicListcreateViewManagers(ReactApplicationContext reactContext){returnArrays.asList(new RCTButton()); }}
然后在MainApplication中的getPackages中進行注冊
5 js端中引用原生端定義的view
'use strict';
import React, { Component } from 'react';
import {
requireNativeComponent
} from 'react-native';
let RTCBtn = requireNativeComponent("RCTButton",RCTButton);
export default class RCTButton extends Component {
render() {
return <RTCBtn {...this.props}/>;
}
}
requireNativeComponent關(guān)聯(lián)js和原生組件世杀,方法中的兩個參數(shù):第一個參數(shù)是原生封裝該UI組件時的名稱持偏,對應(yīng)getName返回值堰氓,第二個參數(shù)是你js端定義的名稱。還可能存在第三個參數(shù)是一個對象
{
nativeOnly:{
myclicked:true
}
}
這個參數(shù)是需要事件傳遞是你定義在android原生端的監(jiān)聽的名稱 如果不加這個在js端直接引入會報錯怔锌。
{...this.props} 必須有,否則組件不顯示贡定。
android端如果想收到事件的傳遞需要復(fù)寫
@Override
public MapgetExportedCustomDirectEventTypeConstants(){returnMapBuilder.builder().put(“這里隨意寫”,MapBuilder.of("registrationName",“這里是你定義的監(jiān)聽的名稱”)).build(); }}
之后才可以收到事件材鹦。
列如js端定義為RTCBtn
<RTCBtn
msg={'“面對疾風(fēng)吧”}
myclicked={(event)=>{
console.log(event.nativeEvent.msg)
}}
/>
記錄一下