JSX和RN样式以及和web的不同之处(js和web有什么区别)
JSX:React中写组件的代码格式, 全称是JavaScript xml
import React from 'react'
import { View, Text } from 'react-native'
const App = () => <View>
<Text>JSX Hello World</Text>
</View>
export default App
RN样式(主要讲解和web开发的不同之处)
flex布局:
- 在rn中默认容器, 布局方式,默认都是flex
- 方向flex-direction: column
样式继承:
- 背景颜色
- 字体颜色
- 字体大小等没有继承
单位:
- 不能加px单位
- 不能加vw、vh等单位
- 可以加百分比单位
#屏幕宽度和高度
import { Dimensions } from 'react-native'
const screenWidth = Math.round(Dimensions.set('window').width)
const screenHeight = Math.round(Dimensions.get('window').height)
#变换
<Text style={{ transform: [{translateY: 300}, {scale: 2}] }}>变换</Text>
标签
- View
- Text
- TouchableOpacity
- Image
- ImageBackground
- TextInput
- 其他 => 1.button 2. FlatList 3.ScrollView 4.StatusBar 5.TextInput
View
1.相当于以前web中的div
2.不支持设置字体大小, 字体颜色等
3.不能直接放文本内容
4.不支持直接绑定点击事件(一般使用TouchableOpactiy 来代替)
Text
1.文本标签,可以设置字体颜色、大小等
2.支持绑定点击事件
TouchableOpacity (onpress => 按下事件 onclick=> 点击事件)
可以绑定点击事件的块级标签
1.相当于块级的容器
2.支持绑定点击事件 onPress
3.可以设置点击时的透明度
import React from 'react'
import {TouchableOpacity, Text} from 'react-native'
const handlePress = () => {
alert('111')
}
const App = () =>
<TouchableOpacity activeOpacity={0} onPress={ handlePress }>
<Text>点击事件</Text>
</TouchableOpacity>
export default App
Image图片渲染
1.渲染本地图片时
<Image source={ require("../gril.png") } />
2.渲染网络图片时, 必须加入宽度和高度
<Image source={{ url: 'https://timgsa.baidu.com/xxx.png }} style={{ width: 200, height: 300 }} />
3.在android上支持GIF和WebP格式图片
默认情况下Android是不支持gif和webp格式的, 只需要在 android/app/build.gradle 文件中根据需要手动添加以下模块:
dependencies {
// 如果你需要支持android4.0(api level 14)之前的版本
implementation 'com.facebook.fresco:animated-base-support:1.3.0'
// 如果你需要支持GIF动画
implementation 'com.facebook.fresco:animated-gif:2.0.0'
// 如果你需要支持webp格式,包括webp动图
implementation 'com.facebook.fresco:animated-webp:2.1.0'
implementation 'com.facebook.fresco:webpsupport:2.0.0'
// 如果只需要支持webp格式而不需要动图
implementation 'com.facebook.fresco:websupport:2.0.0'
}
ImageBackground
一个可以使用图片当做背景的容器,相当于以前的 div + 背景图片
import React from 'react'
import { Text, ImageBackground } from 'react-native'
const App = () =>
<ImageBackground source={require('./assets/logo.png')} style={{ width: 200, height: 200 }}>
<Text>Inside</Text>
</ImageBackground>
export default App
TextInput输入框组件
可以通过 onChangeText 事件来获取输入框的值
语法:
1、组件
2、插值表达式
3、状态state
4、属性props
5、调试
6、事件
7、生命周期
import React from 'react'
import { TextInput } from 'react-native'
const handleChangeText = (text) => {
alert(text)
}
#onChangeText => 获取输入的值
const App = () => <TextInput onChangeText={ handleChangeText } />
export default App
花括号{}里面可以直接添加JS代码的
组件:函数组件, 类组件
函数组件
- 没有state(通过hooks可以有)
- 没有生命周期(通过hooks可以有)
- 适合简单的场景
类组件
- 适合复杂的场景
- 有state
- 有生命周期
最后
- 公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西
- 有兴趣的小伙伴欢迎关注我哦,我是:何小玍。大家一起进步鸭