我的开源项目高仿韩寒的one一个,打算长期维护并借此机会学习react-native相关的技术,感兴趣的可以戳这里 ,此项目不是标准的react-native项目结构,而是在android studio工程项目下引入react-native的混合式开发结构,其中不少地方调用了原生的模块和原生封装的ui组件,相信在react-native跨平台还不成熟的阶段,调用原生完成开发需求是不可避免的,打算在这里对react-native调用原生的相关技术做一个总结.如果有不正确的地方还望指正,或者您有更好的解决方案也欢迎提出一起讨论
调用原生模块 react-native调用原生模块应该是经常会用到的,我们在android studio项目中引入react-native实质上就是设置ReactRootView为activity的布局视图,初始化mReactInstanceManager进行react-native的相关配置,添加自定义的原生组件包,MainReactPackage主组件包,这个是默认添加的,在activity的生命周期中对react-native做相关配置,同时继承DefaultHardwareBackBtnHandler接口,这个接口只有invokeDefaultOnBackPressed的方法,对于android back按键,是在onBackPressed中,把所有的back事件都发到js端,如果js端没监听,或者监听都返回了false,那么就会回到invokeDefaultOnBackPressed的Activity处理。
调用原生的场景 比如我们需要在react-native 的ui中加入toast提示,调用音乐播放等多媒体相关的系统api支持,调用第三方分享和登录授权……不可避免的要调用原生代码,接下来详细记录react-native js端与原生android端之间的通信方式
react-native调用android原生 以加入toast提示为例:
先定义一个ReactContextBaseJavaModule 自定义一个ToastModule继承ReactContextBaseJavaModule,重写其中的getName方法,返回react-native中调用时的组件名,重写getConstants方法,返回一个常量map,定义常量值的key,将所有可供调用的常量值put进去,通过对象.常量值key使用模块常量,使用`@ReactMethod`注解可供react-native调用的方法,@ReactMethod注解的方法返回类型一定是void,这里的回调可以有两种方式实现,第一种是callback的方式,第二种是promise的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 public class ToastModule extends ReactContextBaseJavaModule { private static final String DURATION_SHORT_KEY = "SHORT" ; private static final String DURATION_LONG_KEY = "LONG" ; boolean flag=true ; int count=100000 ; public ToastModule (ReactApplicationContext reactContext) { super (reactContext); } @Override public String getName () { return "ToastNative" ; } @Override public Map<String, Object> getConstants () { final Map<String, Object> constants = new HashMap<>(); constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT); constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG); return constants; } @ReactMethod public void show (String message, int duration ,Callback successCallback, Callback errorCallback) { Toast.makeText(getReactApplicationContext(), message, duration).show(); if (flag) { successCallback.invoke("success" , ++count); } else { errorCallback.invoke("error" , ++count); } flag = !flag; } @ReactMethod public void showMsg (String msg, Promise promise) { String result = "处理结果:" + msg; Toast.makeText(getReactApplicationContext(), result, Toast.LENGTH_SHORT).show(); promise.resolve(result); } @ReactMethod public void showMsg (String message, int duration) { Toast.makeText(getReactApplicationContext(), message, duration).show(); } }
注册ReactContextBaseJavaModule 在自定义的组件包中MyReactPackage注册这个ReactContextBaseJavaModule,其中createViewManagers方法用于注册原生ui组件,而createNativeModules方法用于注册原生模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class MyReactPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules ( ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new UShareModule(reactContext)); modules.add(new ULoginModule(reactContext)); modules.add(new ToastModule(reactContext)); modules.add(new MediaPlayerModule(reactContext)); return modules; } }
这个MyReactPackage是我们自定义的组件包,我们需要添加到配置中
在react-native工程结构下添加自定义的ReactPackage 修改android工程中的Application类,重写ReactNativeHost中的getPackages方法,在返回的数组中添加自定义的组件包对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class MyApplication extends Application implements ReactApplication { public static final MyReactPackage myReactPackage=new MyReactPackage(); private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this ) { @Override public boolean getUseDeveloperSupport () { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages () { return Arrays.<ReactPackage>asList( new MainReactPackage(), myReactPackage ); } }; @Override public ReactNativeHost getReactNativeHost () { return mReactNativeHost; } }
在android studio工程结构下添加自定义的ReactPackage 找到ReactActivity或者继承DefaultHardwareBackBtnHandler接口的activity中的mReactInstanceManager,添加一个自定义的组件包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 private ReactRootView mReactRootView;private ReactInstanceManager mReactInstanceManager; @Override protected void onCreate (@Nullable Bundle savedInstanceState) { super .onCreate(savedInstanceState); ... mReactRootView = new ReactRootView(this ); mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setBundleAssetName("index.android.bundle" ) .setJSMainModuleName("index.android" ) .addPackage(new MainReactPackage()) .addPackage(new MyReactPackage()) .addPackage(new ImagePickerPackage()) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(mLifecycleState) .build(); mReactRootView.startReactApplication(mReactInstanceManager, "SimpleOne" , null ); mReactInstanceManager.getDevSupportManager().showDevOptionsDialog(); setContentView(mReactRootView); ... }
所以只要实现了ReactPackage和ReactContextBaseJavaModule,将它注册到ReactNativeHost或者ReactInstanceManager,就可以在React Native中调用原生模块了。
在react-native中使用 1 2 3 4 import { NativeModules } from 'react-native' ;let toast = NativeModules.ToastNative;toast.show('Toast message' ,toast.SHORT,(message,count)=>{console .log("success" ,message,count)},(message,count)=>{console .log("error" ,message,count)}) toast.showMsg('今晚22:30主播在这里等你' ,toast.SHORT);
这里需要注意的是,callback/promise 在执行invoke/(reject、resolve)之后,都会在js的消息队列中被销毁。callback/promise只能用于一次返回,也就是说不能多次调用callback/promise来与react-native的组件进行通信,在一些场景下这种callback/promise的通信方式是不实用的,比如说我们调用android系统api来播放音乐,我们需要监听音乐的播放状态和进度,这里需要原生模块主动与react-native通信而且是多次通信,我们需要采用另一种通信方式,就是emit,有点类似android的广播,发送一条消息给js端,js端注册监听接收这条消息
Android原生调react-native 以实现播放音乐,监听音乐的播放状态和进度为例,我们需要让android主动向react-native多次发送消息,我们同样需要定义一个ReactContextBaseJavaModule,并且在自定义的组件包MyReactPackage中的createNativeModules方法里注册,跟前面的做法完全一样就不再赘述了,这里我们需要关心的是如何主动发送消息
Android端主动发消息 reactContext在我们注册ReactContextBaseJavaModule的时候由MyReactPackage中的createNativeModules方法传入,通过reactContext得到当前的JSModule调用它的emit方法,可以传两个参数,一个事件名称和一个WritableMap对象,事件名称需要与react-native注册监听的事件名称参数对应起来,而这个WritableMap对象存放的就是所有需要传递的参数
1 2 3 4 5 6 7 8 9 10 public static void sendEvent (ReactContext reactContext, String eventName, WritableMap map) { System.out.println("reactContext=" +reactContext); reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName,map); } WritableMap map=Arguments.createMap(); map.putString("state" ,LOADING_MEDIA_SUCCESS); sendEvent(mContext,PLAY_STATE,map);
react-native注册监听接收消息 这里我们需要对发送的事件名称注册监听,与发送消息时事件名称的传参保持一致,在回调中处理接收到消息以后的逻辑
1 2 3 4 5 6 7 8 9 10 11 this .listener = (reminder ) => { console .log('当前状态' + reminder.state); if (this .props.isVisible){ if (reminder.state === constants.STOP_PLAY_MEDIA || reminder.state === constants.PLAY_EXCEPTION || reminder.state == constants.PLAY_COMPLETE) { this .setState({ isPlay: false , }); } } } DeviceEventEmitter.addListener(constants.PLAY_STATE, this .listener)
如果你在这个回调逻辑中刷新了ui,然而这个页面当前并没绘制,react-native会发出警告,对应的还有取消监听的方法
1 2 DeviceEventEmitter.removeAllListeners(constants.PLAY_STATE); DeviceEventEmitter.removeListener(constants.PLAY_STATE,listener);
这里我们需要注意的是一旦调用了DeviceEventEmitter.removeAllListeners方法,影响的不只有当前页面的监听,所有页面的监听都被移除了,移除当前页面的监听是第二个
调原生ui组件 由于react-native官方提供的滚轮组件可定制性比较低,DatePickerIOS和DatePickerAndroid,调用的都是原生的日期滚轮选择器,也没找到合适的第三方库,无法达到设计的效果,所以采用了自定义原生ui组件的方案,给react-native暴露接口,让react-native调用原生的ui组件,这里我们以自定义日期选择滚轮为例,记录一下react-native调用原生ui组件的过程。
封装组件 绘制单个滚轮 常规方式继承View,在onDraw中用canvas直接绘制,监听手势,根据手指滑动的距离对当前滚轮选项进行刷新。注意一下边界判断,当前选择项下标小于0时,选择最后一项,当前项下标大于最后一项下标,选择第一项。手指抬起时滚动到当前选择项的中间位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 public class WheelView extends View { public static final String TAG = "WheelView" ; public static final float SPEED = 2 ; public static final int SHOW_SIZE = 1 ; private Context context; private List<String> itemList; private int itemCount; private int itemHeight = 50 ; private int currentItem; private Paint selectPaint; private Paint mPaint; private Paint centerLinePaint; private float centerY; private float centerX; private float mLastDownY; private float mMoveLen = 0 ; private boolean isInit = false ; private SelectListener mSelectListener; private Timer timer; private MyTimerTask mTask; Handler updateHandler = new Handler() { @Override public void handleMessage (Message msg) { if (Math.abs(mMoveLen) < SPEED) { mMoveLen = 0 ; if (null != timer) { timer.cancel(); timer.purge(); timer = null ; } if (mTask != null ) { mTask.cancel(); mTask = null ; performSelect(); } } else { mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED; } invalidate(); } }; public WheelView (Context context) { super (context); init(context); } public WheelView (Context context, AttributeSet attrs) { super (context, attrs); init(context); } public void setOnSelectListener (SelectListener listener) { mSelectListener = listener; } public void setWheelStyle (int style) { itemList = WheelStyle.getItemList(context, style); if (itemList != null ) { itemCount = itemList.size(); resetCurrentSelect(); invalidate(); } else { Log.i(TAG, "item is null" ); } } public void setWheelItemList (List<String> itemList) { this .itemList = itemList; if (itemList != null ) { itemCount = itemList.size(); resetCurrentSelect(); } else { Log.i(TAG, "item is null" ); } } private void resetCurrentSelect () { if (currentItem < 0 ) { currentItem = 0 ; } while (currentItem >= itemCount) { currentItem--; } if (currentItem >= 0 && currentItem < itemCount) { invalidate(); } else { Log.i(TAG, "current item is invalid" ); } } public int getItemCount () { return itemCount; } public void setCurrentItem (String selected) { for (int i=0 ; i<itemList.size();i++){ String item=itemList.get(i); if (item.equals(selected)){ currentItem = i; break ; } } resetCurrentSelect(); } public int getCurrentItem () { return currentItem; } @Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { super .onMeasure(widthMeasureSpec, heightMeasureSpec); int mViewHeight = getMeasuredHeight(); int mViewWidth = getMeasuredWidth(); centerX = (float ) (mViewWidth / 2.0 ); centerY = (float ) (mViewHeight / 2.0 ); isInit = true ; invalidate(); } private void init (Context context) { this .context = context; timer = new Timer(); itemList = new ArrayList<>(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStyle(Style.FILL); mPaint.setTextAlign(Align.CENTER); mPaint.setColor(getResources().getColor(R.color.wheel_unselect_text)); mPaint.setTextSize(SizeConvertUtil.spTopx(context, 15 )); selectPaint = new Paint(Paint.ANTI_ALIAS_FLAG); selectPaint.setStyle(Style.FILL); selectPaint.setTextAlign(Align.CENTER); selectPaint.setColor(getResources().getColor(R.color.wheel_select)); selectPaint.setTextSize(SizeConvertUtil.spTopx(context, 17 )); centerLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); centerLinePaint.setStyle(Style.FILL); centerLinePaint.setTextAlign(Align.CENTER); centerLinePaint.setColor(getResources().getColor(R.color.wheel_unselect_text)); } @Override protected void onDraw (Canvas canvas) { super .onDraw(canvas); if (isInit) { drawData(canvas); } } private void drawData (Canvas canvas) { if (!itemList.isEmpty()) { drawCenterText(canvas); for (int i = 1 ; i < SHOW_SIZE + 1 ; i++) { drawOtherText(canvas, i, -1 ); } for (int i = 1 ; i < SHOW_SIZE + 1 ; i++) { drawOtherText(canvas, i, 1 ); } } } private void drawCenterText (Canvas canvas) { float y = centerY + mMoveLen; FontMetricsInt fmi = selectPaint.getFontMetricsInt(); float baseline = (float ) (y - (fmi.bottom / 2.0 + fmi.top / 2.0 )); canvas.drawText(itemList.get(currentItem), centerX, baseline, selectPaint); } private void drawOtherText (Canvas canvas, int position, int type) { int index = currentItem + type * position; if (index >= itemCount) { index = index - itemCount; } if (index < 0 ) { index = index + itemCount; } String text = itemList.get(index); int itemHeight = getHeight() / (SHOW_SIZE * 2 + 1 ); float d = itemHeight * position + type * mMoveLen; float y = centerY + type * d; FontMetricsInt fmi = mPaint.getFontMetricsInt(); float baseline = (float ) (y - (fmi.bottom / 2.0 + fmi.top / 2.0 )); canvas.drawText(text, centerX, baseline, mPaint); } @Override public void setAlpha (int alpha) { } @Override public void setColorFilter (ColorFilter cf) { } @Override public int getOpacity () { return 0 ; } }; super .setBackground(background); } @Override public boolean onTouchEvent (MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: doDown(event); break ; case MotionEvent.ACTION_MOVE: doMove(event); break ; case MotionEvent.ACTION_UP: doUp(); break ; default : break ; } return true ; } private void doDown (MotionEvent event) { if (mTask != null ) { mTask.cancel(); mTask = null ; } mLastDownY = event.getY(); } private void doMove (MotionEvent event) { mMoveLen += (event.getY() - mLastDownY); if (mMoveLen > itemHeight / 2 ) { mMoveLen = mMoveLen - itemHeight; currentItem--; if (currentItem < 0 ) { currentItem = itemCount - 1 ; } } else if (mMoveLen < -itemHeight / 2 ) { mMoveLen = mMoveLen + itemHeight; currentItem++; if (currentItem >= itemCount) { currentItem = 0 ; } } mLastDownY = event.getY(); invalidate(); } private void doUp () { if (Math.abs(mMoveLen) < 0.0001 ) { mMoveLen = 0 ; return ; } if (mTask != null ) { mTask.cancel(); mTask = null ; } if (null == timer) { timer = new Timer(); } mTask = new MyTimerTask(updateHandler); timer.schedule(mTask, 0 , 10 ); } class MyTimerTask extends TimerTask { Handler handler; public MyTimerTask (Handler handler) { this .handler = handler; } @Override public void run () { handler.sendMessage(handler.obtainMessage()); } } private void performSelect () { if (mSelectListener != null ) { mSelectListener.onSelect(currentItem, itemList.get(currentItem)); } else { Log.i(TAG, "null listener" ); } } public interface SelectListener { void onSelect (int index, String text) ; } }
生成日期数据源 封装一个工具类用于生成日期滚轮选择器的数据源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 public class WheelStyle { public static final int minYear = 1980 ; public static final int maxYear = 2020 ; public static final int STYLE_HOUR = 1 ; public static final int STYLE_MINUTE = 2 ; public static final int STYLE_YEAR = 3 ; public static final int STYLE_MONTH = 4 ; public static final int STYLE_DAY = 5 ; public static final int STYLE_LIGHT_TIME = 7 ; private WheelStyle () { } public static List<String> getItemList (Context context, int Style) { if (Style == STYLE_HOUR) { return createHourString(); } else if (Style == STYLE_MINUTE) { return createMinuteString(); } else if (Style == STYLE_YEAR) { return createYearString(); } else if (Style == STYLE_MONTH) { return createMonthString(); } else if (Style == STYLE_DAY) { return createDayString(); } else if (Style == STYLE_LIGHT_TIME) { return createWeekString(context); } else { throw new IllegalArgumentException("style is illegal" ); } } private static List<String> createHourString () { List<String> wheelString = new ArrayList<>(); for (int i = 0 ; i < 24 ; i++) { wheelString.add(String.format("%02d" , i)); } return wheelString; } private static List<String> createMinuteString () { List<String> wheelString = new ArrayList<>(); for (int i = 0 ; i < 60 ; i++) { wheelString.add(String.format("%02d" , i)); } return wheelString; } private static List<String> createYearString () { List<String> wheelString = new ArrayList<>(); for (int i = minYear; i <= maxYear; i++) { wheelString.add(Integer.toString(i)+'年' ); } return wheelString; } private static List<String> createMonthString () { List<String> wheelString = new ArrayList<>(); for (int i = 1 ; i <= 12 ; i++) { wheelString.add(String.format("%02d" , i)+'月' ); } return wheelString; } private static List<String> createDayString () { List<String> wheelString = new ArrayList<>(); for (int i = 1 ; i <= 31 ; i++) { wheelString.add(String.format("%02d" , i)); } return wheelString; } private static List<String> createWeekString (Context context) { List<String> wheelString = new ArrayList<>(); String[] timeString = context.getResources().getStringArray(R.array.weeks); for (String week : timeString) { wheelString.add(week); } return wheelString; } public static List<String> createDayString (int year, int month) { List<String> wheelString = new ArrayList<>(); int size; if (isLeapMonth(month)) { size = 31 ; } else if (month == 2 ) { if (isLeapYear(year)) { size = 29 ; } else { size = 28 ; } } else { size = 30 ; } for (int i = 1 ; i <= size; i++) { wheelString.add(String.format("%02d" , i)); } return wheelString; } private static boolean isLeapMonth (int month) { return month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ; } private static boolean isLeapYear (int year) { return (year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 ; } }
自定义LinearLayout绘制整个滚轮视图 由2个滚轮组成的滚轮视图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 public class PickDateView extends LinearLayout { private static final String TAG = "PickDateView原生Tag" ; CallBack callBack; WheelView yearWheel; WheelView monthWheel; public interface CallBack { void changeYear (int year) ; void changeMonth (int month) ; void onSure (int year, int month, long time) ; } public void setCallBack (CallBack callBack) { this .callBack = callBack; } public PickDateView (Context context) { super (context); addCustomLayout(context); } public void setYear (String year) { yearWheel.setCurrentItem(year); } public void setMonth (String month) { monthWheel.setCurrentItem(month); } private void addCustomLayout (Context context) { LayoutInflater mInflater = LayoutInflater.from(context); View contentView = mInflater.inflate(R.layout.wheel_select_date, null ); yearWheel = (WheelView) contentView.findViewById(R.id.select_date_wheel_year_wheel); monthWheel = (WheelView) contentView.findViewById(R.id.select_date_month_wheel); yearWheel.setWheelStyle(WheelStyle.STYLE_YEAR); yearWheel.setOnSelectListener(new WheelView.SelectListener() { @Override public void onSelect (int index, String text) { int selectYear = index + WheelStyle.minYear; if (callBack != null ) { callBack.changeYear(selectYear); } } }); monthWheel.setWheelStyle(WheelStyle.STYLE_MONTH); monthWheel.setOnSelectListener(new WheelView.SelectListener() { @Override public void onSelect (int index, String text) { int selectMonth = index + 1 ; if (callBack != null ) { callBack.changeMonth(selectMonth); } } }); Button sureBt = (Button) contentView.findViewById(R.id.select_date_sure); sureBt.setOnClickListener(new OnClickListener() { @Override public void onClick (View v) { int year = yearWheel.getCurrentItem() + WheelStyle.minYear; int month = monthWheel.getCurrentItem(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); long setTime = calendar.getTimeInMillis(); if (callBack != null ) { callBack.onSure(year, month, setTime); } } }); addView(contentView); } }
给react-native暴露接口 自定义ViewManager,继承SimpleViewManager设置需要暴露的ui组件类PickDateView,重写实例化方法createViewInstance在方法内实例化ui组件类,同时在回调被调用时通知js端,发送事件消息,也是通过WritableMap传递参数列表,用@ReactProp
注解标注的方法在react-native中作为属性传入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 public class PickDateViewManager extends SimpleViewManager <PickDateView > { private static final String REACT_CLASS = "PickDateView" ; private static final String TAG = "PickDateViewManger原生Tag" ; private PickDateView pickDateView; @Override public String getName () { return REACT_CLASS; } @Override protected PickDateView createViewInstance (final ThemedReactContext reactContext) { pickDateView=new PickDateView(reactContext); pickDateView.setCallBack(new PickDateView.CallBack() { @Override public void changeYear (int year) { WritableMap map = Arguments.createMap(); map.putInt("target" , pickDateView.getId()); map.putString("msg" , "year: " + year); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( pickDateView.getId(), "topChange" , map ); } @Override public void changeMonth (int month) { WritableMap map = Arguments.createMap(); map.putInt("target" , pickDateView.getId()); map.putString("msg" , "month: " + month); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( pickDateView.getId(), "topChange" , map ); } @Override public void onSure (int year, int month, long time) { WritableMap map = Arguments.createMap(); map.putInt("target" , pickDateView.getId()); WritableMap params=Arguments.createMap(); params.putInt("year" ,year); params.putInt("month" ,month); params.putString("time" ,time+"" ); map.putMap("msg" , params); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( pickDateView.getId(), "topChange" , map ); } }); return pickDateView; } @ReactProp (name = "setYear" ) public void setYear (PickDateView pickDateView,String year) { pickDateView.setYear(year); } @ReactProp (name = "setMonth" ) public void setMonth (PickDateView pickDateView,String month) { pickDateView.setMonth(month); } }
注册自定义的ViewManager 同样需要在自定义的组件包MyReactPackage的createViewManagers方法中注册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class MyReactPackage implements ReactPackage { @Override public List<ViewManager> createViewManagers (ReactApplicationContext reactContext) { List<ViewManager> viewManagers=new ArrayList<>(); viewManagers.add(new PickDateViewManager()); viewManagers.add(new ShowPlayViewManager()); return viewManagers; } }
在react-native中使用 在react-native中声明原生组件 定义原生中也声明了的组件属性和统一接收回调消息的onChange方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import React from 'react' ;import PropTypes from 'prop-types' ;import {requireNativeComponent, View} from 'react-native' ;let iface = { name: 'PickDateView' , propTypes: { setYear: PropTypes.string, setMonth: PropTypes.string, onChange: PropTypes.func, ...View.propTypes } } let RCTPickDateView = requireNativeComponent('PickDateView' , iface);export default RCTPickDateView;
在react-native中使用原生组件 绘制一个弹窗,弹窗内部使用原生的日期滚轮选择器,在弹窗弹出时加入一个展开动画,在onChange方法中接收参数obj.nativeEvent.参数名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 import React, { Component } from 'react' ;import { AppRegistry, StyleSheet, Text, View, Modal, Animated, TouchableOpacity } from 'react-native' ; import PickDateView from '../view/PickDate' ;import constants from '../Constants' ;let {width, height} = constants.ScreenWH;class PullPickDate extends Component { constructor (props){ super (props); this .onLayout=this .onLayout.bind(this ); this .state={ expanded: false , animation : new Animated.Value() }; } showAnimation(height){ let maxHeight=height; let minHeight=0 ; let initialValue = this .state.expanded ? maxHeight + minHeight : minHeight, finalValue= this .state.expanded ? minHeight : maxHeight + minHeight; this .setState({ expanded: !this .state.expanded }); console .log('最大高度' +maxHeight); console .log('初始值' +initialValue+'最终值' +finalValue); this .state.animation.setValue(initialValue); this .timer = setTimeout( () => { this .toggle(finalValue); }, 5000 ); } toggle(finalValue) { Animated.spring( this .state.animation, { toValue: finalValue } ).start(); } render() { return ( <Modal animationType={'none' } transparent={true } visible={this .props.onShow} onRequestClose={() => { this .props.onCancel(); }}> <View style={{width : width, flex : 1 , marginTop : height * 0.08 + 0.12 * width,backgroundColor : 'rgba(0, 0, 0, 0.7)' }}> <PickDateView setYear={this .props.year} setMonth={this .props.month} onLayout={this .onLayout} onChange={(obj) => { console .log('onSure收到事件' + obj.nativeEvent.msg + "目标id" + obj.nativeEvent.msg.year); let year = obj.nativeEvent.msg.year + '' ; let month = obj.nativeEvent.msg.month + '' ; let time= obj.nativeEvent.msg.time + '' ; if (year !== 'undefined' && month !== 'undefined' ) { this .props.onCancel(); }else { this .props.onSure(year,month,time); } }} style={{width : '100%' , flex : 0.42 ,}}/> <TouchableOpacity style={{flex :0.58 }} onPress={() => this .props.onCancel()}/> </View> </ Modal> ); } onLayout(event){ this .showAnimation(event.nativeEvent.layout.height); } } export default PullPickDate;