1.View
作为创建UI时最基础的组件,View通常用作容器,它可以放到其它的视图里,也可以有任意多个任意类型的子视图,支持Flexbox布局。View: UI构建的基石,一切页面的起点。
- flexDirection:横向纵向布局
- flexGrow和flex的比较尺寸
- 属性传数值和百分比
- position: absolute绝对定位下仍然受父级属性影响
事例一、
下面的例子创建了一个View,包含了三个有颜色的方块,并且设置了一个内边距:
import React, {Component} from "react";
import {View} from "react-native";
export default class CompontsTest extends Component {
render() {
return (
<View style={{ backgroundColor: "#fff", flex: 1, padding: 20}}>
<View style={{flex: 1,flexDirection:"row", backgroundColor: 'powderblue'}}/>
<View style={{flex: 2, backgroundColor: 'skyblue'}} />
<View style={{flex: 3, backgroundColor: 'steelblue'}} />
</View>
)
}
}
事例二:
import { StyleSheet, View } from "react-native"
export default () => {
return (
<View style={styles.parent}>
<View style={styles.child1}></View>
{/* <View style={styles.child2}></View>
<View style={styles.child3}></View> */}
</View>
)
}
const styles = StyleSheet.create({
parent: {
width: '100%',
height: '100%',
flexDirection: 'row',
backgroundColor: '#e5e5e5',
justifyContent: 'center'
},
child1: {
width: '100%',
height: '100%',
backgroundColor: '#ff0000',
position: 'absolute',
},
child2: {
width: '100%',
height: '100%',
backgroundColor: '#00ffff'
},
child3: {
width: '100%',
height: '100%',
backgroundColor: '#ff00ff'
},
});
由于child1在主轴上是居中的,即使被position: 'absolute'修饰,但是由于没有主轴方向上的位置,即这里的left和right,所以subview1这里还是居中的,如果想要其距离左边20,在 justifyContent: 'center'不动的情况下,只需要child1加入left: 20即可,即
child1: {
width: '100%',
height: '100%',
backgroundColor: 'red',
position: 'absolute',
left: 20
},
事例三 :获取布局信息onLayout
(1)React Native 开发的应用可以有一个或者多个根 View(没有父组件)。
(2)在不指定根 View 的宽高(并将其 flex 样式设为 1)的情况下,通过指定这个根 View 组件的回调函数可以很方便地得到设备的放置状态。
- 当设备横置时,通过 onLayout 回调取到的根 View 宽大于高。
- 当设备竖置时,通过 onLayout 回调取到的根 View 宽小于高。
(3)同时 onLayout 回调函数还可以用来监测设备放置状态的改变,并得到改变后的新的屏幕高度和宽度。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Dimensions,
View,
Text,
} from 'react-native';
class Main extends Component {
//根View的onLayout回调函数
_onLayout(event) {
//使用大括号是为了限制let结构赋值得到的变量的作用域,因为接来下还要结构解构赋值一次
{
//获取根View的宽高,以及左上角的坐标值
let {x, y, width, height} = event.nativeEvent.layout;
console.log('通过onLayout得到的宽度:' + width);
console.log('通过onLayout得到的高度:' + height);
}
//通过Dimensions API获取屏幕宽高
let {width, height} = Dimensions.get('window');
console.log('通过Dimensions得到的宽度:' + width);
console.log('通过Dimensions得到的高度:' + height);
}
render() {
return (
<View style={styles.flex} onLayout={this._onLayout}>
</View>
);
}
}
const styles = StyleSheet.create({
flex:{
flex:1, //将更View的flex样式设为1,且不指定根View的宽和高。
alignItems: 'center'
},
});
AppRegistry.registerComponent('HelloWorld', () => Main);
2.Text
Text 是 React Native 中用于显示文本内容的组件。它类似于 Web 开发中的 <span> 或 <p> 标签,但专为移动端优化。Text 组件支持嵌套、样式化和触摸事件,是构建用户界面的基础组件之一。
使用语法
<Text
color="#333333"
lineHeight="12"
fontSize="12" >简单教程</Text>
属性说明
属性 | 类型 | 是否必填 | 说明 |
---|---|---|---|
selectable | bool | false | 是否可选中,true 为真,false 为否 |
numberOfLines | number | false | 用于在计算文本布局(包括换行)后使用省略号截断文本,使得总行数不超过此数字 |
ellipsizeMode | string | false | 如果设置了 numberOfLines,那么该属性用于设置文本如何被截断 |
color | string | false | 用于设置如何转换文本中的某些子文本 |
fontFamily | string | 否 | 用于设置文本的字体 |
fontSize | number | 否 | 用于设置文字的大小 |
fontWeight | string | 否 | 文字的粗细,可以设置的值有: 'normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900' |
lineHeight | number | 否 | 用于设置文本的行高 |
textAlign | string | 否 | 用于设置文本的对其方式,可选的值有 'auto', 'left', 'right', 'center', 'justify'。Android 下只有 left 即使设置了其它值扔就是 left |
textShadowColor | color | 否 | 用于设置文本的阴影色 |
textShadowOffset | object | 否 | 用于设置阴影的偏移量,格式为 {width: number,height: number} |
letterSpacing | number | 否 | 用于设置字与字之间的距离 |
组件嵌套
文本组件 `` 可以嵌套另一个组件,被嵌套的组件会继承父级的文本组件的样式和属性。
<Text
color="#333333"
lineHeight="12"
fontSize="12" >简单教程
<Text
fontSize="11"
>简单编程</Text>
</Text>
完整示例:
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native'
const App = () => {
return (
<View style = {styles.container}>
<Text style = {styles.text}>
<Text style = {styles.capitalLetter}>
B
</Text>
<Text>
UCT
</Text>
<Text>
BU<Text style = {styles.wordBold}>编程</Text> 怎样学习全英文课程
</Text>
<Text style = {styles.italicText}>阅读文档
</Text>
<Text style = {styles.textShadow}>
习惯全英文素材
</Text>
</Text>
</View>
)
}
export default App
const styles = StyleSheet.create ({
container: {
alignItems: 'center',
marginTop: 100,
padding: 20
},
text: {
color: '#41cdf4',
},
capitalLetter: {
color: 'red',
fontSize: 20
},
wordBold: {
fontWeight: 'bold',
color: 'black'
},
italicText: {
color: '#37859b',
fontStyle: 'italic'
},
textShadow: {
textShadowColor: 'red',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius : 5
}
})
3.Image:精美的UI从使用图片开始
3.1属性说明
属性 | 说明 |
---|---|
source | 图片源的两种类型 |
resizeMode | 缩放模式 |
blurRadius | 曾经的难题现在如此简单 |
defaultSource | 占位图片 |
fadeDuration | 渐入动画时间 |
onLoad、onError | 加载成功和加载失败 |
tintColor | 着色 |
示例:
import { View, Image, StyleSheet } from "react-native"
import { imageUri } from '../constants/Uri.js'
import avator from '../assets/images/avatar.png'
import setting from '../assets/images/icon_setting.png'
import { useEffect } from "react"
export default () => {
return <View style={styles.root}>
<Image
style={styles.img}
source={setting}
// source={{ uri: 'xxxx' }}
// source={avator}
// fadeDuration={3000}
// blurRadius={3}
onLoad={(event) => {
console.log(event.nativeEvent);
}}
onError={(event) => {
console.log(event.nativeEvent);
}}
onLoadStart={(event) => {
}}
onLoadEnd={(event) => {
}}
/>
</View>
}
const styles = StyleSheet.create({
root: {
width: '100%',
height: '100%',
backgroundColor: '#c0c0c0'
},
img: {
width: 200,
height: 200,
resizeMode: 'contain',
tintColor: 'white'
}
})
3.2Image.getSize、Image.prefetch 解析图片的尺寸信息
useEffect(() => {
Image.getSize(imageUri, (width, height) => {
console.log(`width: ${width}, height: ${height}`)
}, (error) => {
console.log(error);
})
Image.prefetch(imageUri).then((result) => {
console.log(result);
}).catch(e => {
console.log(e);
})
}, [])
3.3ImageBackground:View和Image的合体
import { ImageBackground, StyleSheet, View, Image, Text } from "react-native"
import bg_card from '../assets/images/bg_card.png'
import icon_bank from '../assets/images/icon_bank.png'
export default () => {
return <View style={styles.root}>
<ImageBackground
style={styles.imageBackgroundStyle}
imageStyle={styles.imageStyle}
source={bg_card}
>
<Image
style={styles.imgStyle}
source={icon_bank}
/>
<View style={styles.txtContainer}>
<Text style={styles.topDesc}>
招商银行
</Text>
<Text style={styles.middleDesc}>
储蓄卡
</Text>
<Text style={styles.lastDesc}>
●●●● ●●●● ●●●● 3068
</Text>
</View>
</ImageBackground>
</View>
}
const styles = StyleSheet.create({
root: {
width: '100%',
height: '100%',
flexDirection: 'column',
padding: 10
},
imageBackgroundStyle: {
width: '100%',
height: 150,
flexDirection: 'row',
},
imageStyle: {
borderRadius: 12,
resizeMode: 'cover'
},
imgStyle: {
width: 48,
height: 48,
marginTop: 20,
marginLeft: 20,
},
txtContainer: {
width: '100%',
height: '100%',
flexDirection: 'column',
marginTop: 20,
marginLeft: 20,
},
topDesc: {
fontSize: 18,
fontWeight: 'bold',
color: 'white'
},
middleDesc: {
fontSize: 16,
color: 'A0A0A0',
marginTop: 5
},
lastDesc: {
color: 'white',
marginTop: 30
},
});
4. TextInput:输入框组件
二、API
3.1属性说明
属性 | 说明 |
---|---|
autoCapitalize | 枚举类型,用于信息提示,可选值包括none、sentences、words、characters |
placeholder | 占位符,在输入前显示文本内容 |
value | 文本框输入的内容 |
placeholderTextColor | 如果为true,显示为密码输入框,文本显示为"*"号 |
editable | 如果为false,文本框不可以输入,默认为true |
keyboardType | 枚举类型,表示键盘类型,可选值包括'default','email-address','numeric','phone-pad','ascii-capable' |
autoFocus | 如果为true,将自动聚焦 |
clearButtonMode | 枚举类型,用于显示清除按钮,可选值包括never、while-editing、unless-editing、always |
maxLength | 能够输入的最长字符数 |
enablesReturnKeyAutomatically | 如果为true,表示无文本时键盘不显示返回键,默认为false |
onBlur | 失去焦点触发事件 |
onFocus | 获取焦点触发事件 |
onChange | 当文本发生改变时,调用该函数 |
onchangeText | 当文本的输入框内容发生改变时调用。它会接收一个文本的参数对象 |
onsubmitEditing | 当结束编辑后,点击键盘的提交按钮时触发事件 |
示例:
import React, { useRef, useEffect } from 'react';
import {
SafeAreaView,
StyleSheet,
View,
TextInput
} from 'react-native';
export default () => {
const inputRef = useRef(null);
useEffect(() => {
setTimeout(() => {
// inputRef.current.blur();
}, 2000);
}, []);
return (
<View style={styles.root}>
<TextInput
ref={inputRef}
style={styles.input}
// autoFocus={true}
blurOnSubmit={true}
caretHidden={false}
// defaultValue="默认内容"
editable={true}
keyboardType='number-pad'
returnKeyType='search'
// maxLength={11}
// multiline={true}
// numberOfLines={2}
onFocus={() => {
}}
onBlur={() => {
}}
onChange={(event) => {
console.log(event.nativeEvent);
}}
onChangeText={(text) => {
console.log(text);
}}
// selection={{start: 0, end: 3}}
selectionColor='red'
selectTextOnFocus={true}
secureTextEntry={true}
/>
</View>
);
}
const styles = StyleSheet.create({
root: {
width: '100%',
height: '100%',
backgroundColor: '#F0F0F0',
},
input: {
width: '100%',
height: 56,
backgroundColor: '#D0D0D0',
fontSize: 24,
color: '#333333',
fontWeight: 'bold',
},
});