在react native中没有html标签 只能使用组件
import React, {useState} from 'react'
import {View, Text, Button, StyleSheet} from 'react-native'
// 跟普通的Web的react不同 RN当中不能使用html标签 只能使用RN提供的组件
const App = () => {
const [a, setA] = useState(5)
const fn1 = () => {
setA(a + 1)
}
return (
// 在组件中应用样式
<View style={styles.astyle}>
<Text>123</Text>
<Text>{a}</Text>
// RN当中没有click 所有组件支持的事件是不一样的
// 不是所有组件都有onPress点击事件
<Button title='我是按钮' onPress={fn1}></Button>
</View>
)
}
// 在RN当中 样式都要通过StyleSheet的create方法来创建样式
// RN组件的样式 并不能完全的套用 Web当中的css
// 不同的组件 支持的样式时不同的
// 每个组件都会在它的style的属性说明中说明有它支持的样式内容
const styles = StyleSheet.create({
astyle: {
// 样式中的长度没有单位 均为与设备像素密度无关的逻辑像素点
// 且RN当中的flex弹性盒布局的默认主轴方向为竖轴column
borderWidth: 5,
borderColor: '#ff6600',
borderStyle: 'solid'
}
})
export default App
引入在线图片
引入时必须指定宽高
<Image source={{uri: 'https://facebook.github.io/react/logo-og.png'}}
style={{width: 400, height: 400}} />
引入本地图片
引入Android的assets目录下的图片需要添加前缀asset:/
引入时必须指定宽高
<Image source={{uri: 'asset:/app_icon.png'}}
style={{width: 40, height: 40}} />
引入Android的drawable目录下的图片 不带路径也不带后缀
引入时必须指定宽高
<Image source={{uri: 'app_icon'}}
style={{width: 40, height: 40}} />
(仅Android)使用Android原生的elevation API来设置视图的高度,这样可以为视图添加一个投影
并且会影响视图的层叠顺序,此属性仅支持Android5.0
值为number
在RN中建议使用函数式组件开发
import React from 'react' // React一定要引入 不管是否需要使用
import {View, Text} from 'react-native'
import style from './style' // 模块化 将css抽离出来作为同目录下文件
const Home = () => {
return (
<View>
<Text> 首页 </Text>
</View>
)
}
export default Home
// 创建文件 utils/size.js
import { Dimensions } from 'react-native';
// 这里的宽度和高度 得到的就是官档中的逻辑像素点的值
const deviceWidthDp = Dimensions.get('window').width; // 得到设备的宽度
const deviceHeightDp = Dimensions.get('window').height; // 得到屏幕的高度
console.log('deviceWidthDp', deviceWidthDp, deviceHeightDp);
// 这里的uiWidthPx uiHeightPx 是你的设计稿的宽高尺寸
let uiWidthPx = 750;
let uiHeightPx = 1400;
// 如果应用是横屏的用pTd
export const pTd = uiElePx => {
return (uiElePx * deviceHeightDp) / uiHeightPx;
};
// 如果应用是竖屏的用pTx 在app开发当中很少用到
export const pTx = uiElePx => {
return (uiElePx * deviceWidthDp) / uiWidthPx;
};
引入到需要使用的组件后 然后使用函数进行转换
import {pTx, pTd} from '../utils/size.js'
// code...
const styles = StyleSheet.create({
astyle: {
// 根据实际测量的效果图当中的元素的实际大小 使用pTd来进行转换
borderWidth: pTd(5),
borderColor: '#ff6600',
borderStyle: 'solid'
}
})