1.react-native-vector-icons集成度气,顯示圖片顯示問題涉兽。
要使用字體庫的字體妻往,除了執(zhí)行npm install react-native-vector-icons --save 之外,
1.npm install react-native-vector-icons --save
2.
react-native link react-native-vector-icons
// 或者
npm install -g rnpm
rnpm link react-native-vector-icons
還需要再Android與iOS工程里面進行相應的配置,Android的話需要在 android/app/build.gradle 中添加:apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
如果在android原生應用集成了react native形式蔚龙,路徑為"apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"",不然檢測不到。資料
使用方法:
1.import Icon from "react-native-vector-icons/Ionicons"
Icon圖標鏈接
2.import FontAwesome from "react-native-vector-icons/FontAwesome"
FontAwesome圖標鏈接
<Icon name="md-american-football" size={64}></Icon>
3.import EIcon from "react-native-elements/src/icons/Icon";
使用 react _native_elements的圖標映胁,使用type,來加載不同類型下的木羹。
elements圖標
eg:
<EIcon
reverse //反轉(zhuǎn)
name='ac-unit'
type='MaterialIcon'
color='#517fa4'
/>
2.webstrom設置React native代碼模板鏈接
3.循環(huán)遍歷,提示W(wǎng)arning: Each child in an array or iterator should have a unique "key" prop. Check the render ...
解決方法:循環(huán)的時候加個key={i} 雖然并沒啥用解孙,但是必須加4.react-native-scrollable-view詳解是詳解
在使用sctollable-view的過程中坑填, renderTabBar={()=><DefaultTabBar />}默認的是一頁分布排列,當數(shù)量過多弛姜,就顯示不出來脐瑰,換成 renderTabBar={()=><ScrollableTabBar />},能滾動廷臼。就能正常顯示了苍在。但是還一直說為啥沒數(shù)據(jù)≤蹋坑了寂恬。
5.調(diào)試技巧參考資料 資料2
6.解決 調(diào)試跨域的問題
下載google瀏覽器跨域插件鏈接。密碼:fxtx
打開更多工具===擴展插件莱没,脫動下載好的插件進行安裝初肉,
重新啟動瀏覽器。就沒有錯誤了郊愧。正常顯示
7.Debug JS Remotely google瀏覽器提示 無法找到文件
重新安裝了下瀏覽器朴译,就可以了、
8.fetch 中的POST請求傳遞的請求參數(shù)沒起作用属铁。
后使用fromData()形式提交眠寿,不需要header,就能請求成功
let formData = new FormData();
formData.append('pid', this.state.pid);
fetch(NET_URL, {
method: 'POST',
body: formData
}).then((response)=>response.json())
.then((responseData)=>{
this.setState({
new_tabs:responseData.data
})
})
.catch((error)=>{
})
這樣子就能正常顯示了。
9.警告3:調(diào)試警告
看下報的警告就知道調(diào)試程序在這個窗口導致運行緩慢焦蘑,所以建議你換一個單獨新的窗口進行調(diào)試
10.Uncaught SyntaxError: Unexpected token
應該是用法的錯誤盯拱,我遇到過,最后是因為導入的路徑的問題例嘱。一般是JS代碼出錯了狡逢,要么是樣式或者布局不正確引起
11.
image.png
該問題是因為在return 中注釋的問題鏈接
12.Warning: Failed child context type: Invalid child context virtualizedCell.cellKey of type number supplied to CellRenderer, expected string.
參考:資料
13.unable to connect with remote debugger Timeout while connecting to remote debugger
,不管是真機還是模擬器都要在setting中設置自己的ip地址 eg:10.1.1.100:8081
10.1.1.100是你的ip地址奢浑,在cmd窗口 ipconfig 查看自己的ip地址
14.出現(xiàn)bundling failed: NotFoundError: Cannot find entry file index.android.js in any of the roots
For Android, go to your Module: app’s build.gradle and add the following above the line: apply from: “../../node_modules/react-native/react.gradle”
project.ext.react = [
entryFile: “index.js”
]
In MainApplication.java, you need to override another function in the anonymous ReactNativeHost class by adding this:
@Override
protected String getJSMainModuleName() {
return "index";
}
16. SyntaxError: Unexpected token < in JSON at position 0
使用fetch的get,返回的不是json字符串,導致
17.在react native界面點擊物理返回鍵腋腮,把當前的Activity銷毀了雀彼,React native中的js,沒有返回壤蚜。其實在集成的時候,RN都給我們做好了徊哑,只是亂改代碼導致錯誤袜刷,還半天沒解決到。
書讀百遍莺丑,其義自見(xian)
感謝文章的小伙伴從Android到React Native開發(fā)(二著蟹、通信與模塊實現(xiàn))
DefaultHardwareBackBtnHandler
DefaultHardwareBackBtnHandler接口,通過它我們可以整體了解梢莽,React Native從android端萧豆,到JS端對back按鍵事件的處理。
首先Activity需要繼承DefaultHardwareBackBtnHandler接口昏名。DefaultHardwareBackBtnHandler只有一個invokeDefaultOnBackPressed方法炕横。
ReactInstanceManager在onHostResume(Activity activity, DefaultHardwareBackBtnHandler defaultBackButtonImpl);中需要傳入activity和handler接口。
ReactInstanceManager.onBackPressed()會通過DeviceEventManagerModule葡粒,向js端發(fā)送了"hardwareBackPress"消息。
[熱點]React Native對于android back按鍵膜钓,是在onBackPressed中嗽交,把所有的back事件都發(fā)到js端,如果js端沒監(jiān)聽颂斜,或者監(jiān)聽都返回了false夫壁,那么就會回到繼承了DefaultHardwareBackBtnHandler接口,實現(xiàn)了invokeDefaultOnBackPressed的Activity處理沃疮。
推薦使用 AppCompatActivity implements DefaultHardwareBackBtnHandler這種方式集成盒让。連接中也給了說法。
@Override
public void invokeDefaultOnBackPressed() {
ToastUtils.showShortToast("js默認返回結束調(diào)用執(zhí)行Activity銷毀");//重要
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause(this);
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
}
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
ToastUtils.showShortToast("js返回");//重要
} else {
super.onBackPressed();//不會走這里
ToastUtils.showShortToast("ceshi");
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
我都快哭了我..............................
18.
image.png
寫成'/reactjs/js/news'會報錯司蔬,要從根項目.開始
19.react-native-router-flux 根據(jù)原生的傳值邑茄,跳轉(zhuǎn)不同的界面
render() {
let title = this.props.title
let tag_id = this.props.tag_id
return<Router>
<Scene key="root">
<Scene key="home" component={News} title={title} />
<Scene key="mine" component={Tab} initial={tag_id == "1" ? true : false} title={title} message={title}/>
</Scene>
</Router>
}
message是向tab組件傳值過去,用this.props.message來獲取
20.isMounted(...)is deprecated in plain JavaScript React classes解決方法
首先俊啼,出現(xiàn)此錯誤提示的原因是源代碼內(nèi)有已被React舍棄的代碼肺缕,但此并不影響程序運行。
在index.js 內(nèi)寫入以下代碼可屏蔽此提示授帕。
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
21.webstrom上傳代碼到github
使用WebStorm/IDEA上傳本地項目到GitHub
忽略文件
然后在進行提交
SSH Key若果有創(chuàng)建過就不用創(chuàng)建的同木。
在另外一臺電腦上,拉取跛十,然后彤路,就可以兩臺電腦協(xié)同合作。
22. Cannot find module node_modules\react-native\local-cli\cli.js'
npm install ,然后:npm install重新安裝以后芥映,配置
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global
23.verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...imer-mixin":"^0.13.2"'
從網(wǎng)絡上拉去項目洲尊,報錯远豺,解決
npm -g i npm@4連接
24.Native module VectorIconsModule tried to override VectorIconsModule for module name RNVectorIconsModule. If this was your intention, set canOverrideExistingModule=true
找到MainApplication.java(android/app/src/main/java/com),里面有有重復的引用颊郎,把重復的部分刪除就行了
25.React Native Undefined is not an object(evaluating ‘_react2.PropTypes.func’)
import React, { Component, PropTypes } from 'react';失效應該用下面的寫法憋飞。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
把PropTypes 從prop-types 中引入
26.使用react-native-swiper,從網(wǎng)絡加載數(shù)據(jù),圓點不滾動姆吭,停留在第一個榛做。圖片數(shù)量錯亂
<Swiper
key={this.state.image.length}
style={styles.swiper}
>
添加key.參考資料
27 xx is invalid;it must be a function, usually from the 'prop-type' package,but received 'string'
28.在使用react-native-scrollable-tab-view+flatlist實現(xiàn)功能的時候,用了scrollview包裹了list,這讓我犯了很大的錯誤内狸。浪費了很多的時間
<ScrollableTabView tabBarBackgroundColor='#fff' //tab欄目背景色
tabBarActiveTextColor='#cb1c23'//選中的文字顏色
tabBarInactiveTextColor='#333'//為選中的文字顏色
tabBarUnderlineStyle={styles.tabBarUnderline}
tabBarTextStyle={styles.text_style}
renderTabBar={()=><ScrollableTabBar />}>
{
this.state.new_tabs.map((item,index)=>{
return <NewsList type_id={item.id} tabLabel={item.name} key={index} />
})
}
</ScrollableTabView>
上面是正確的寫法检眯。
29,react native使用mobx , can't find variable:Symbol
- 把mobx降版本到 4.3.1 . mobx-react降版本到 5.1.0 即可.或者
- 在.babelrc配置文件 增加 ployfill插件 "babel-plugin-transform-runtime"即可
{
"presets": [
"react-native"
],
"plugins": [
"transform-decorators-legacy",
"babel-plugin-transform-runtime"
]
}
30,There are multiple mobx instances active. This might lead to unexpected results
31.react native 刪除第三方庫,刪干凈那種昆淡。锰瘸。。
鏈接
首先需要刪除在RN的package.json中的依賴昂灵,輸入一下命令:
npm uninstall --save react-native-video避凝,
如果是組件作為devDependencies,需要加上-D眨补,
如果是從optionalDependencies中刪除管削,還需要加上-o的參數(shù),
我為了保險能刪干凈撑螺,直接輸入一下命令:
npm uninstall -s -D -O 組件名
32.npm 安裝第三方庫的指定的版本
npm install --save 庫名@2.8.1
或者yarn add [package]@[version]
32 Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0
這個直接用webstrom運行android產(chǎn)生的含思,后面直接用了android studio來直接運行,就略過了這個問題甘晤,不在消耗時間來解決他了
33.第一次運行react-native start 提示throw er; // Unhandled 'error' event
原因端口被占了含潘。
參考資料資料
34.react-native項目刪除node_module文件夾,重新加載
yarn install
35 Debug模式下View config not found for name RCTView
不調(diào)試的時候线婚,是可以運行的遏弱。
出現(xiàn)這種錯誤是因為在React 中,組件的名字必須是大寫字母開頭酌伊,
36.java.lang.RuntimeException: Tried to access a JS module before the React instance was fully set up. Calls to ReactContext#getJSModule should only happen once initialize() has been called on your native module.
37 Module AppRegistry is not a registered callable module(calling runApplication)
Module AppRegistry is not a registered callable module (calling runApplication)
原因:卸載了三方庫腾窝,運行,但是此時出入熱加載模式居砖,注冊重復虹脯,關閉熱加載就行了
參考文章文章
38 解決React Native的Image組件中不更新圖片的問題,采用base64顯示
情景:使用百度云拍照識別數(shù)字返回給RN,每次攜帶的image_url都是一個地址奏候,而rn中的image組件對相同的地址是有緩存的循集,所有拍照之后,一直都是顯示的第一張蔗草,所以在android端把實際地址轉(zhuǎn)成base64,傳到RN咒彤,讓RN讀取base64的疆柔,就能實現(xiàn)啦
部分代碼:
android中設置
public static String imageToBase64() {
String path=Environment.getExternalStorageDirectory()+ "/shuiwu_pic/"+ "water.jpg";
if (TextUtils.isEmpty(path)) {
return null;
}
InputStream is = null;
byte[] data;
String result = null;
try {
is = new FileInputStream(path);
//創(chuàng)建一個字符流大小的數(shù)組。
data = new byte[is.available()];
//寫入數(shù)組
is.read(data);
//用默認的編碼格式進行編碼
result = Base64.encodeToString(data, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
獲取base64字符串
onScanningResult = (result) => {
let baseImg=`data:image/png;base64,${result.image_url}`;
this.setState({
image_url:baseImg,
real_num: result.result === "識別失敗" ? "0" : result.result
})
}
镶柱。旷档。。
<Image source={{uri:this.state.image_url}}
style={styles.image}/>}
39, react-native 傳base64到七牛
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if(xhr.readyState===4&&xhr.status===200)
{
let res=JSON.parse(xhr.responseText)
console.log("filekey"+res.key)
}
}
xhr.open("post","http://upload.qiniup.com/putb64/-1/",true)
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.setRequestHeader("Authorization", "UpToken " + 你從服務器獲取的token);
xhr.send(this.state.image_base64)
40歇拆,react-native webview中圖片以寬度自適應
let reg= new RegExp("<img", "g")
return (
<View style={styles.container}>
<WebView
style={styles.webview}
bounces={false}
scalesPageToFit={true}
renderError={
()=>{
return <ErrorPage/>
}
}
source={{html: this.state.info.item.item.content.replace(reg,"<img style='max-width:100%;height:auto'")}}
/>
</View>
);
41.react-native android 打包 出現(xiàn)問題
刪除自動生成的drawable目錄下的文件
參考資料
42鞋屈,react-native-router-flux 下點擊android返回鍵2秒內(nèi)推出
return <Router
backAndroidHandler={()=>{
console.log(Actions.state)
if(Actions.state.index===0) {
if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
//最近2秒內(nèi)按過back鍵,可以退出應用故觅。
// return false;
BackHandler.exitApp();//直接退出APP
}else{
this.lastBackPressed = Date.now();
ToastAndroid.show('再按一次退出應用', 1000);//提示
return true;
}
}
}}>
<Scene key="root">
<Scene key="login" component={LoginPage} initialPage={true} hideNavBar={true} />
</Scene>
</Router>
43厂庇,react-native 上傳圖片或者文件到七牛
1.上傳base64位圖片到七牛,核心代碼
var url = "http://upload.qiniup.com/putb64/-1/";
var xhr = new XMLHttpRequest();
xhr.open("post", url, true);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.setRequestHeader("Authorization", "UpToken " + this.state.qiniu_token);
xhr.send(pic);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
//自己的邏輯
let res = JSON.parse(xhr.responseText)
let file_key = this.state.img_header + res.key
var img_arr = this.state.select_img_urls
img_arr.push({'url': file_key})
var img_keys = this.state.select_img_keys
img_keys.push(res.key)
this.setState({
select_img_urls: img_arr,
select_img_keys: img_keys,
})
EasyLoading.dismiss()
console.log('選取圖片數(shù)組select_img_urls1', this.state.select_img_urls)
return file_key
} else {
}
}
原生js方式上傳文件[視頻]到七牛输吏,
參考文章:文章
let realpath="file://"+path
console.log("絕對路徑",realpath)
let names=path.split("/")
let name_key=names[names.length-1]
console.log("名稱",name_key)
let formData=new FormData()
formData.append("file",{uri:realpath,type:"application/octet-stream",name:name_key})
// formData.append("key",name_key),不設置权旷,服務器會隨機生成hash值
formData.append("token",this.state.qiniu_token)
let options={}
options.body=formData
options.method="POST"
console.log("上傳的參數(shù)",JSON.stringify(formData))
fetch("http://upload.qiniup.com/",options)
.then(response => response.json())
.then(res=>{
console.log("成功",res)
res.filename=name_key
}).catch((e)=>{
console.log("異常",e.toString())
})
注意
:這樣傳到七牛倒源,七牛返回的文件名是沒有中文的妄田,可以自己在拿到的結果中處理
44 warnOnce could not be found within the project
45 cli-platform-android/native_modules.gradle找不到指定的路徑
androidstudio中直接刪除
46 react-native webview與react-native通信
情景再現(xiàn):webview中有多張圖片,點擊某張圖片锦针,就能查看大圖它浅。結合react-native-image-zoom-viewer庫查看大圖
在webview核心代碼
render() {
let reg= new RegExp("<img", "g")
let html_source=`<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<body>
<button style="display: none" onClick="hhh(11)" id="btn">點擊</button>
${this.state.content.replace(reg,"<img style='max-width:100%;height:auto;width:100%'")}
<script>
(function hhh(text) {
let hideButon= document.getElementById('btn')
let images= document.getElementsByTagName("img")
hideButon.innerHTML=images.length;
let imgarr=[]
for (let i=0;i<images.length;i++){
let url_img=images[i].src
imgarr.push(url_img)
images[i].onclick=function() {
let data={"item":imgarr,"index":i}
window.ReactNativeWebView.postMessage(JSON.stringify(data));
}
}
})(window)
</script>
</body>
</html>`
const {imgs,index} = this.state
let arr = []
imgs.map((item) => {
let dic = {url:item}
arr.push(dic)
})
return (
<View style={styles.container}>
<WebView
style={styles.webview}
ref={webview => { this.webview = webview; } }
bounces={false}
scalesPageToFit={true}
renderError={
()=>{
return <ErrorPage/>
}
}
source={{html: html_source}}
onMessage={(e) => {
console.log("接收",e.nativeEvent.data)
let arr = JSON.parse(e.nativeEvent.data).item
let arr_index=JSON.parse(e.nativeEvent.data).index
this.setState({
imgs: arr,
index:arr_index,
is_show:true,
})
}}
startInLoadingState={true}
/>
<Modal visible={this.state.is_show} transparent={true}>
<ImageViewer onClick={() => {
this.setState({
is_show:false
});
}} imageUrls={arr} index={index} />
</Modal>
</View>
);
}
}
function hhh是立即執(zhí)行函數(shù)坤邪,使用<button style="display: none" onClick="hhh(11)" id="btn">點擊</button>來綁定觸發(fā)。
window.ReactNativeWebView.postMessage(JSON.stringify(data));
來傳遞參數(shù)
onMessage={(e) => {
console.log("接收",e.nativeEvent.data)
let arr = JSON.parse(e.nativeEvent.data).item
let arr_index=JSON.parse(e.nativeEvent.data).index
this.setState({
imgs: arr,
index:arr_index,
is_show:true,
})
}}
webview中接收參數(shù)
注意
const {imgs,index} = this.state
let arr = []
imgs.map((item) => {
let dic = {url:item}
arr.push(dic)
})
如果在model中直接使用this.state.imgs和this.state.index是訪問不了的,有問題罚缕,所有使用上面的代碼進行傳遞
47 React Native——嵌套WebView中的返回處理
連接感謝
情景再現(xiàn),詳情使用react-native-webview的控件的webview加載一個url.這個網(wǎng)頁能一層一層的點擊怎静,但是返回的話邮弹,一下就整個界面就返回出去了,所以蚓聘,腌乡。。夜牡。
核心代碼
監(jiān)聽返回鍵
componentDidMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
}
}
//android自帶返回鍵
onBackAndroid = () => {
if (this.state.backButtonEnabled) {
this.webview.goBack();
return true;
} else {
Actions.pop()
return true;
}
}
componentWillUnmount(): void {
if (Platform.OS === 'android') {
this.listenter.remove()
}
}
自定義返回鍵
_left_button() {
return <TouchableWithoutFeedback onPress={() => {
if (this.state.backButtonEnabled) {
this.webview.goBack();
return true;
} else {
Actions.pop()
return true;
}
}
}><Image
style={{width: Size(48), height: Size(48), marginLeft: Size(32),marginTop:ifIphoneXNavTitle() + Size(32) * 2,position:'absolute'}}
source={require('../../../res/image/ic_left_arrows.png')}/></TouchableWithoutFeedback>;
}
....
onNavigationStateChange = navState => {
this.setState({
backButtonEnabled: navState.canGoBack
});
};
....
<WebView
ref={'webView'}
source={{uri: this.state.url}} //此處URL為服務器返回的html
ref={webview => { this.webview = webview; } }
javaScriptEnabled={true}
// onLoadEnd={this.pageOnLoaded.bind(this)}
onNavigationStateChange={this.onNavigationStateChange}
/>
注意
:需要解綁与纽,別忘了,不然退出不了app,
48 viewpagerAndroid is error in the reactnative0.61
1.yarn add @react-native-community/viewpager
- react-native link @react-native-community/viewpager
- 在源碼中
react-native-scrollable-tab-view/index.js
const ViewPagerAndroid = require('@react-native-community/viewpager')
49 node_modules\realpath-native\index.js: Module
fs` does not exist in the Haste module map
把index.js文件內(nèi)容全部注釋
50 react-native-scrollable-tab-view 橫向切換時點擊事件會觸發(fā)塘装,進入二級界面問題急迂。
不使用RN的 TouchableWithoutFeedback等點擊,使用 import {TouchableWithoutFeedback} from 'react-native-gesture-handler'
注意在:在android的MainActivity中增加
import { TouchableNativeFeedback, TouchableHighlight, TouchableOpacity, TouchableWithoutFeedback } from 'react-native-gesture-handler' 點擊沒效果蹦肴,android 中MainActivity中增加
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
...
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
就ok了
51 android fetch request failed
https://github.com/facebook/react-native/issues/28551
let formdata=new FormData()
let file={uri:response.uri,type:"multipart/form-data",name:"image.jpg"}
formdata.append("image",file)
fetch(urls.file_update,{
method:"POST",
headers: {
'Content-Type': 'multipart/form-data;charset=utf-8',
"accept": "application/json",
"token": this.state.token,
"staff": this.state.staff_id,
},
body:formdata,
}).then((response) => response.json())
.then(res=>{
console.log("數(shù)據(jù)",res)
}).catch(e=>{
console.log("異常",e.toString())
})
react-native 上傳圖片詳解
封裝過的:
let formdata={
"image":{uri:response.uri,type:"multipart/form-data",name:"image.jpg"}
}
HttpUtils.fetch_request(urls.file_update,"post",formdata).then(res=>{
console.log("數(shù)據(jù)",res)
}).catch(e=>{
console.log("異常",e.toString())
})
使用rn-fetch-blob上傳圖片
RNFetchBlob.fetch("POST", urls.file_update,
{
"token": this.state.token,
"staff": this.state.staff_id.toString(),
'Content-Type': 'multipart/form-data'
}, [
{name: "image", filename: filename, type: "image/jpg", data: RNFetchBlob.wrap(fileuri)}
]
).then(response => response.json())
.then(res => {
console.log("成功", res)
}).catch(e => {
console.log("異常", e.toString())
})
注意:body 僚碎,參數(shù)是以數(shù)組形式添加,name:就是傳遞的參數(shù)名稱
react-native 實現(xiàn)上傳功能
52 關于react 父級組件更新數(shù)據(jù)觸發(fā)子組件更新渲染問題
感謝http://www.reibang.com/p/7049b035766b
53 VSCode yarn : 無法加載文件 C:\Users\Administrator\AppData\Roaming\npm\yarn.ps1阴幌,因為在此系統(tǒng)上禁止運行腳本勺阐。
set-ExecutionPolicy RemoteSigned
不是內(nèi)部命令卷中,不是在cmd中使用哦,要打開windows powershell
shift+鼠標右鍵在當前文件夾打開
windows powersshell,切換到管理員 Start-Process powershell -Verb runAs
以管理員身份執(zhí)行set-ExecutionPolicy RemoteSigned
54 使用ant-design/react-native,手機端組件
yarn add @ant-design/react-native babel-plugin-import @react-native-community/viewpager @ant-design/icons-react-native
并新建 .babelrc文件 渊抽,
{
"plugins": [
["import", { libraryName: "@ant-design/react-native" }] // 與 Web 平臺的區(qū)別是不需要設置 style
]
}
上面第二組件是按需加載蟆豫,第三個是使用到tabs,android端需要的懒闷。
55ant design mobile圖標不顯示問題
yarn add @ant-design/react-native
注意:拷貝到android\app\src\main\assets\fonts文件夾下哦十减,
56 react-native 修改端口號,親測可用
找到根目錄 metro.config.js
module.exports = {
//新增
server: {
port: 8083,
},
};
注意:保存代碼之后在運行下 android原生項目
57 react-native-map3d地圖毛雇,
天地圖坐標轉(zhuǎn)成高德地圖坐標嫉称,在react-native-map3d上展示
參考鏈接
const pi = 3.14159265358979324;
const a = 6378245.0;
const ee = 0.00669342162296594323;
//注意在參考鏈接中,參數(shù)位置是寫反了得
outOfChina(lat, lon)
{
if ((lon < 72.004 || lon > 137.8347)&&(lat < 0.8293 || lat > 55.8271)){
console.log("在國外")
return true;
}else {
console.log("在國內(nèi)")
return false;
}
}
transformLat(x,y)
{
let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
return ret;
}
transformLon(x,y)
{
let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
return ret;
}
transform(wgLat,wgLon)
{
console.log("經(jīng)緯度",wgLat)
console.log("we",wgLon)
let mars_point={lon:0,lat:0};
if (this.outOfChina(wgLat, wgLon))
{
mars_point.lat = wgLat;
mars_point.lon = wgLon;
return ;
}
console.log("經(jīng)緯度",typeof wgLat)
let dLat = this.transformLat(wgLon - 105.0, wgLat - 35.0);
let dLon = this.transformLon(wgLon - 105.0, wgLat - 35.0);
let radLat = wgLat / 180.0 * pi;
let magic = Math.sin(radLat);
magic = 1 - ee * magic * magic;
let sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
mars_point.lat = wgLat + dLat;
mars_point.lon = wgLon + dLon;
return mars_point
}
調(diào)用transformLat
高德地圖坐標轉(zhuǎn)天地圖坐標
const pi = 3.14159265358979324;
transformGCJ2WGS(gcjLat, gcjLon) {
let d =this.delta(gcjLat, gcjLon)
return {
'lat': gcjLat - d.lat,
'lon': gcjLon - d.lon
}
}
delta(lat, lon) {
let a = 6378245.0 // a: 衛(wèi)星橢球坐標投影到平面地圖坐標系的投影因子灵疮。
let ee = 0.00669342162296594323 // ee: 橢球的偏心率织阅。
let dLat = this.transformLat(lon - 105.0, lat - 35.0)
let dLon = this.transformLon(lon - 105.0, lat - 35.0)
let radLat = lat / 180.0 * 3.14159265358979324
let magic = Math.sin(radLat)
magic = 1 - ee * magic * magic
let sqrtMagic = Math.sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI)
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI)
return {
'lat': dLat,
'lon': dLon
}
}
transformLat(x, y) {
let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x))
ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0
ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0
ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0
return ret
}
transformLon(x, y) {
let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x))
ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0
ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0
ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0
return ret
}
58.去掉黃色警告
console.ignoredYellowBox = ['Warning: BackAndroid is deprecated. Please use BackHandler instead.','source.uri should not be an empty string','Invalid props.style key'];
console.disableYellowBox = true //