您的位置:首页 > Web前端 > React

Android React Native的使用细节问题

2015-11-20 13:26 591 查看
踩了几天React Native Android的坑。总结为一句话,目前android学习react native还为时过早,坑太多,需要你慢慢去踩。就目前来讲,能踩的坑基本上都踩了一遍,所以还是等它稳定下来再去学吧,否则会浪费掉一大堆时间。

单位

在React Native中,组件的宽度,高度都是不用写单位的,你写个100,在Android中代表的到底是100px还是100dp,就不得而知了,这时候自己实践一下就一目了然了。

window.width={Dimensions.get('window').width+"\n"}
window.height={Dimensions.get('window').height+"\n"}
pixelRatio={PixelRatio.get()}

);
}
});" data-snippet-id="ext.7bfb646561fe67a5326cbf4ef608053e" data-snippet-saved="false" data-csrftoken="D0aGxWSM-Z-gCjvyW3XSBeveq1XPkNr28YpU" data-codota-status="done">[code]var Dimensions = require('Dimensions');
var PixelRatio = require('PixelRatio');

var AwesomeProject = React.createClass({
render: function() {
return (
<Text style={styles.test}>
window.width={Dimensions.get('window').width+"\n"}
window.height={Dimensions.get('window').height+"\n"}
pixelRatio={PixelRatio.get()}
</Text>

);
}
});


在我的小米3上,输出的是,而我的小米3的分辨率是1080*1920

window.width=360
window.height=640
pixelRatio=3


显然输出的是dp的单位,那么如果要转成对应的px的单位怎么转呢,答案就在上面的pixelRatio,将dp单位* pixelRatio就是对应的px的值了,同理px/pixelRatio就是对应的dp的值了。和android中px与dp的转换是一样的。

图片

图片的显示需要指定宽度和高度,否则不会显示

图片资源加载可以从远处加载,也可以从本地加载

远处加载的方式如下

<Image source={{uri:'http://your.host/your.png'}}


这种方式的优势是引入方式简单,更新方便,只需要替换server上的图片即可,不需要修改源代码

缺点也很明显,即初次请求图片时,需要请求server,图片过大的,请求的延时会很大

本地加载需要注意的是图片需要打包,然后据说可以加载手机本地图片,然而我测试了n遍无果,根本加载不进来

" data-snippet-id="ext.ebaf3fd8c32d616c21e1f0f5d250abfd" data-snippet-saved="false" data-csrftoken="M2nhZ3Aw-4XgyXqgT-4T9siRdYM66LnRzVpE" data-codota-status="done">[code]   <Image style={{width:100,height:100}} source={{isStatic: true, uri: '/sdcard/icon.png' }}/>


除了加载本地资源,还可以加载静态资源,这个资源需要打包才能使用,也就是不能使用服务器获取js的方式,必须打包后放在assets目录下才能使用,测试后发现也没有什么卵用。

<Image source={ require('image!icon') } />


系统

如果要判断当前系统是android还是ios,从而进行一些适配工作,可以使用Platform

{Platform.OS}

);
}
});" data-snippet-id="ext.35d6e79f1b2aecd15192d4905cdeb595" data-snippet-saved="false" data-csrftoken="BUmP1AAG-BQrRmb6FnIwiU9dvJUgmcncplRk" data-codota-status="done">[code]var Platform = require('Platform');

var AwesomeProject = React.createClass({
render: function() {
return (
<View>
<Text>
{Platform.OS}
</Text>
</View>
);
}
});


如果在android中,界面会输出android,如果在ios中会输出ios,当然上面的Platform也可以这么定义

var {
AppRegistry,
StyleSheet,
Text,
View,
Platform
} = React;


Toast的使用

有时候为了方便测试,经常会toast,React Native为android也提供了这么一个组件ToastAndroid ,使用方法如下

var ToastAndroid = require('ToastAndroid');
ToastAndroid.show('提示的信息', ToastAndroid.SHORT);


或者

var {
AppRegistry,
StyleSheet,
Text,
View,
ToastAndroid
} = React;
ToastAndroid.show('提示的信息', ToastAndroid.SHORT);


flex布局

View默认宽度为100%

当flexDirection的值为column时, justifyContent:’center’为垂直居中, alignItems:’center’为水平居中

当flexDirection的值为row时, justifyContent:’center’为水平居中, alignItems:’center’为垂直居中

定位

和css的标准不同的是, 元素父容器不用设置position:’absolute|relative’ 。默认相对于父容器进行位移。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息