reactNative基础组件

内置组件

View

  • 视图容器,作用相当于 htmldiv 标签,它是创建UI所需的最基础组件,支持Flexbox布局、样式、触摸事件,它可以放到其它视图中,也可以包含任意多个任意子视图。
  • https://reactnative.cn/docs/view/
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
import React, { Component } from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';

export default class ViewTest extends Component {
render() {
return (
{/* View标签相当于div,可以嵌套 */}
<View style={style.container}>
<View>
<Text>React Native</Text>
</View>
<View>
<Text>使用React编写</Text>
<Text>使用JSX编写</Text>
</View>
</View>
);
}
}
// 注意border、background等样式不能简写,必须一个一个的设置属性
let style = StyleSheet.create({
container: {
width: 300,
padding: 10,
borderStyle: "dashed",
borderWidth: 2,
borderColor: "red",
borderRadius: 2,
},
text: {
fontSize: 20,
color: "yellow",
}
});

Text

  • 文本容器,作用相当于 htmlspan 标签,为什么不是 p 标签呢,一会演示。Text标签支持嵌套、触摸事件。在RN中,文本必须放置到Text中才可以被渲染,否则报错。
  • 注意: 除了Text外, 别的组件内都不能包含文本
  • https://reactnative.cn/docs/text/

文本布局

Text采用的是文本布局,多个子文本在渲染时会折叠合并在一起,如果把View理解成块级元素,那么Text就可以理解为行内元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import React, { Component } from "react";
import { StyleSheet, View, Text } from "react-native";

export default class TextTest extends Component {
render() {
return (
// 可以嵌套
<Text>

<Text>饿了吗</Text>
<Text>美图</Text>
</Text>
);
}
}

文本样式

在RN中,父文本的样式可以传递给后代文本,也就是样式继承。但是除了文本之外其它组件都无法继承样式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
render() {
return (
<Text style={style.rootText}>
<Text>饿了吗</Text>
<Text>美图</Text>
{/* 文本样式继承 */}
<Text>
<Text>滴滴外卖</Text>
</Text>
</Text>
);
}

let style = StyleSheet.create({
rootText: {
fontSize: 20,
color: "blue",
lineHeight: 24
}
});
分享