面对现代手机五花八门的屏占比 不知道宽度的情况下可以使用
import { Dimensions } from 'react-native';
const DimenStyle = Dimensions.get('window');
//屏幕宽度
DimenStyle.width;
//高度
DimenStyle.height;
// 手机端独有组件是状态栏展示
StatusBar
// 手机loading提示信息
Activitylndicator
import {Button, Alert} from 'react-native';
<Botton
title='' // 名称
color='' // 按钮的颜色
onPress={() => {
// 原生alert也可以使用
alert('我是一个按钮')
// 组件 不带title
Alert.alert('我是一个按钮');
Alert.alert(
'警告提示',
'警告内容',
[{ // 顺序会影响按钮布局 样式部分手机生效
text: '取消',
onPress:() => console.log('取消'),
style: 'cancel'
},{
text: '确认',
onPress:() => console.log('确认'),
style: 'default'
},{
text: '稍后再试',
onPress:() => console.log('稍后再试'),
}]
)
}} // 类似于点击事件
>
</Botton>
import {Switch, StatusBar, View} from 'react-native';
const statusBar = false;
<View>
<StatusBar
hidden={true} // true 隐藏手机状态条 默认为false
backgroundColor='' // 尽在安卓有效 状态栏颜色
barStyle=''
//三个选项 bark-content 变成黑色图标 light-content 白色图标
/>
//开关
<Switch
tackColor={{false: 'red', true: 'green'}} // 背景颜色
thumbColor={'blue'} // 前景颜色
value={statusBar}
onValueChange={() => {statusBar = !statusBar}}
/>
</View>
import {View, ActivityIndicator, Platform} from 'react-native';
if(Platform.OS === 'android') {
安卓应用
} else if(Platform.OS === 'ios') {
苹果应用
}
<View>
<ActivityIndicator
color='' // 颜色
// 数字指定大小仅限于安卓
size='' // 大 large 小 small 数值也可以
/>
</View>
安装 和 苹果显示不同
import {View, Image} from 'react-native';
// marginVertical 外边距
// paddingHorizontal 水平方向内边距
<View>
<Image
style={} // 样式
source={ //图片路径
// require('./2.jpg') //本地图片
uri: 'http://xxx.png' // 线上网址或者base64格式的图片
}
/>
</View>
import {View, TextInput} from 'react-native';
<View>
<TextInput // 输入框,默认没有边框
style='' //样式
placeholder='' //提示信息
value='' // 展示信息
// 键盘类型 就会调起数字键盘 更多请看官网
keyboardType='number-pad'
multilint={true} // 启用多行
numberOfLines={5} // 多行数
textAilgnVertical='top' // 统一 文字位置
secureTextEntry={true} // 密码属性
onValueChange={() => {}} // 方法
/>
</View>
import {
View,
TouchableHighlight,
TouchableOpacity,
TouchableWithoutFeedback
} from 'react-native';
<View>
<TouchableHighlight
onPress={()=> { // 触碰时方式
}}
>
<View>触碰高亮</View>
</TouchableHighlight>
<TouchableOpacity
onPress={()=> { // 触碰时透明底变化
}}
>
<View>透明底变化</View>
</TouchableOpacity>
<TouchableWithoutFeedback
onPress={()=> { // 触碰时无响应
}}
>
<View>无响应</View>
</TouchableWithoutFeedback>
</View>
import {View, ScrollView, SafeAreaView} from 'react-native';
<View>// 安卓 无法滑动到最底部 需要最底下有标签高度
<ScrollView // 内容超出滚动
style={}
contentContainerStyle={} // 针对内容的样式
showVerticalScrollIndcator={} // 隐藏滚动条
horizontal={true} //横向滚动
>
</ScrollView>
</View>
安全视图
SafeAreaView
import React from "react";
import { StyleSheet, Text, View, SafeAreaView, SectionList, StatusBar } from "react-native";
const DATA = [
{
title: "标题1", // 标题
data: ["Pizza", "Burger", "Risotto"] // 数据
}
];
const Item = (item:any) => (
<View style={styles.item}>
<Text style={styles.title}>{item.title}</Text>
</View>
);
const App = () => (
<SafeAreaView style={styles.container}>
<SectionList
sections={DATA}//存放数据
keyExtractor={(item, index) => item + index} //key
renderItem={({ item }) => <Item title={item} />} // 每一个列表项的默认渲染器
renderSectionHeader={({ section }) => { // 展示title
return <Text style={styles.header}>{section.title}</Text>
}}
// 添加列表头部
ListHeaderComponent={() => (
<Text>我列表标题</Text>
)}
// 添加列表底部
ListFooterComponent={() => (
<Text>到底了!!!!</Text>
)}
// 触发下拉刷新到底部 0.1 -----> 10%
onEndReachedThreshold={0.1}
// 触发下拉事件
onEndReached={() => {
console.log('到底了???')
}}
// loading 效果
refreshing={isLoading}
// 上拉触发事件
onRefresh={onRefresh}
// 没有数据时展示
ListEmptyComponent={() => (
<Text>空空如也</Text>
)}
// 分隔符每一项的
ItemSeparatorComponent={() => (
<View style={[styles.separator]}/>
)}
/>
</SafeAreaView>
);
const styles = StyleSheet.create({
container: {
// flex: 1,
paddingTop: StatusBar.currentHeight,
marginHorizontal: 16
},
item: {
backgroundColor: "#f9c2ff",
padding: 20,
marginVertical: 8
},
header: {
fontSize: 32,
backgroundColor: "#fff"
},
title: {
fontSize: 24
}
});
export default App;
import React, {useState} from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar, Platform ,TouchableOpacity} from 'react-native';
const DATA = [
{
id: 'bd7a11113abb28ba',
title: '1头条',
];
const App = () => {
const [isLoading, setIsLoading]= useState(false)
const [selsetdID, setSelsetdID]= useState(null);
const renderItem = ({ item }:any) => {
const backgroundColor = item.id === selsetdID ? 'blue' : 'pink'
return (
<TouchableOpacity
style={styles.item}
onPress={() => setSelsetdID(item.id)}
>
<Text style={[styles.title, { backgroundColor }]}>{item.title}</Text>
</TouchableOpacity>
);
};
const onRefresh = (cal?: any) => {
console.log('触发下拉刷新')
setIsLoading(true);
setTimeout(() => {
setIsLoading(false);
console.log('刷新列表成功');
}, 3000)
}
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
// 默认滚动位置
initialScrollIndex={1}
// 默认提前加载
initialNumToRender={4}
// 列数
numColumns={1}
// 反转倒置
inverted={false}
// 默认选中ID
extraData={selsetdID}
// 水平模式
// horizontal={true}
// 添加列表头部
ListHeaderComponent={() => (
<Text>我列表标题</Text>
)}
// 添加列表底部
ListFooterComponent={() => (
<Text>到底了!!!!</Text>
)}
// 触发下拉刷新到底部 0.1 -----> 10%
onEndReachedThreshold={0.1}
// 触发下拉事件
onEndReached={() => {
console.log('到底了???')
}}
// loading 效果
refreshing={isLoading}
// 上拉触发事件
onRefresh={onRefresh}
// 没有数据时展示
ListEmptyComponent={() => (
<Text>空空如也</Text>
)}
// 分隔符每一项的
ItemSeparatorComponent={() => (
<View style={[styles.separator]}/>
)}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
separator: {
borderWidth: 1,
borderColor: 'red',
margin: 10
}
});
export default App;
import React, { useEffect, useRef } from "react";
import { Animated, Text, View, StyleSheet, Button } from "react-native";
const App = () => {
// fadeAnim will be used as the value for opacity. Initial Value: 0
const fadeAnim = useRef(new Animated.Value(0)).current;
const containerAnim = useRef(new Animated.Value(0)).current;
const fadeIn = () => {
Animated.timing(fadeAnim, {
toValue: 1, // 目标值
duration: 3000, // 时间
useNativeDriver: true // 启用原生模式
}).start();// 启动
};
const fadeOut = () => {
Animated.timing(fadeAnim, {
toValue: 0,
duration: 3000,
useNativeDriver: true
}).start(() => {// 结束执行
console.log('动画执行结束');
});
};
// 组件加载 开启动画
useEffect(() => {
scanMove()
}, []);
const scanMove = () => {
Animated.timing(containerAnim, {
toValue: 200,
duration: 2000,
useNativeDriver: true
}).start(() => {// 结束执行
console.log('动画执行结束');
scanMoveEnd()
});
}
const scanMoveEnd = () => {
Animated.timing(containerAnim, {
toValue: 0,
duration: 2000,
useNativeDriver: true
}).start(() => {// 结束执行
console.log('动画执行结束');
scanMove()
});
}
return (
<View style={styles.container}>
<Animated.View
style={[
styles.fadingContainer,
{
opacity: fadeAnim
}
]}
>
<Text style={styles.fadingText}>Fading View!</Text>
</Animated.View>
<View style={styles.buttonRow}>
<Button title="Fade In" onPress={fadeIn} />
<Button title="Fade Out" onPress={fadeOut} />
</View>
<View style={styles.scanningContainer}>
<Animated.View
style={[
styles.containerStyle,
{
transform:[{
translateY: containerAnim
}]
}
]}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
containerStyle: {
height: 1,
width: 200,
backgroundColor: "powderblue"
},
fadingContainer: {
paddingVertical: 8,
paddingHorizontal: 16,
backgroundColor: "powderblue"
},
fadingText: {
fontSize: 28,
textAlign: "center",
margin: 10
},
buttonRow: {
flexDirection: "row",
marginVertical: 16
},
scanningContainer: {
width: 200,
height: 200,
borderColor: 'blue',
borderWidth: 1
}
});
export default App;
npm install react-native-webview
//---------
const [url,setUrl] = useState('http://www.baidu.com');
const webView:any = useRef(null)
const [urlInput,setUrlInput] = useState(url);
//页面加载完成触发
const webViewOnLoad = (syntheticEvent: { nativeEvent: any; }) => {
const {nativeEvent} = syntheticEvent;
const curl = nativeEvent.url;
//根据url地址判断刚才已经完成什么操作
const jmurl = decodeURIComponent(curl);
setUrlInput(jmurl);
console.log("网页加载完成,地址是:"+jmurl)
};
//接收web发送过来的信息
const onMessage = (event: { nativeEvent: { data: any; }; }) => {
const rep = event.nativeEvent.data;
//console.log('-----------webview返回结果--------------');
let minLog = rep;
if (rep.length > 300) {
minLog = rep.substring(0, 290); //日志太长影响观感
}
console.log(minLog);
};
return (
<SafeAreaView style={{flex:1}}>
<View style={{height:40,flexDirection:'row',justifyContent:'space-between'}}>
<TextInput
style={{flex:1, height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => setUrlInput(text)}
value={urlInput}
/>
<Button title={"转到"} onPress={()=>{
setUrl(urlInput);
}}/>
</View>
<WebView source={{uri: url}}
ref={(webVieww) => {webView.current = webVieww}}
// sharedCookiesEnabled={true}
// startInLoadingState={true}
// onLoad={webViewOnLoad}
// onMessage={onMessage}
onError={syntheticEvent => {
const {nativeEvent} = syntheticEvent;
console.log('网络连接失败!');
console.warn('WebView error: ', nativeEvent);
}}
/>
<View style={{flexDirection:'row',justifyContent:'space-between',height:40,backgroundColor:'white'}}>
<Button title={"主页"} onPress={()=>{
setUrl('http://www.baidu.com?t='+new Date().getTime());
}}/>
<Button title={"后退"} onPress={()=>{
webView.current.goBack();
}}/>
<Button title={"前进"} onPress={()=>{
webView.current.goForward();
}}/>
<Button title={"刷新"} onPress={()=>{
webView.current.reload();
}}/>
</View>
</SafeAreaView>);
};
//-----------
<WebView
originWhitelist={['*']}
source={{html: '11111
'}}
/>
yarn add @react-native-picker/picker
// 注意安卓和ios不同效果
// 需要不同配置
import React, { useState } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import { Picker } from '@react-native-picker/picker';
const App = () =>
{
let users = [
{ label: '请选择常用的聊天软件', value: '' },
{ label: 'QQ', value: '' },
{ label: '微信', value: '' },
{ label: '飞书', value: '✈' },
]
const [user, SetUser] = useState('')
const upDataUser = (user: any) =>
{
console.warn(user);
SetUser(user)
}
return (
<View style={styles.container}>
<Text>请选择常用的聊天软件</Text>
{/* 设置选择器 */}
<Picker
selectedValue={user}
placeholder='请选择常用的聊天软件'
mode={'dropdown'} // 弹出方式 仅次于安卓
onValueChange={(e: any) => upDataUser(e)}>
{
// 设置选项
users.map((data, index) =>
<Picker.Item key={index} label={data.label} value={data.value} />
)
}
</Picker>
<Text style={styles.label}>你的选择是:</Text>
<Text style={styles.text}>{user} </Text>
</View>
)
}
export default App
const styles = StyleSheet.create({
container: {
margin: 50
},
label: {
fontSize: 14,
color: '#333'
},
text: {
fontSize: 30,
alignSelf: 'center',
color: 'pink'
}
})
// import Swiper from 'react-native-swiper';
import { StyleSheet, Text, View, Image, Dimensions, SafeAreaView } from 'react-native'
import React from 'react'
import Swiper from 'react-native-swiper';
const dimensions = Dimensions.get('window');
export default function swiper() {
return (
<SafeAreaView style={{flex: 1}}>
<Swiper
style={styles.swiper} //样式
height={200} //组件高度
loop={true} //如果设置为false,那么滑动到最后一张时,再次滑动将不会滑到第一张图片。
autoplay={true} //自动轮播
autoplayTimeout={2} //每隔4秒切换
horizontal={true} //水平方向,为false可设置为竖直方向
paginationStyle={{bottom: 10}} //小圆点的位置:距离底部10px
showsButtons={false} //为false时不显示控制按钮
showsPagination={false} //为false不显示下方圆点
dot={
<View style={{ //未选中的圆点样式
backgroundColor: 'rgba(0,0,0,.2)',
width: 18,
height: 18,
borderRadius: 4,
marginLeft: 10,
marginRight: 9,
marginTop: 9,
marginBottom: 9,
}}/>
}
activeDot={
<View style={{ //选中的圆点样式
backgroundColor: '#007aff',
width: 18,
height: 18,
borderRadius: 4,
marginLeft: 10,
marginRight: 9,
marginTop: 9,
marginBottom: 9,
}}/>
}
>
<Image source={{uri: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_source%2F81%2Ff8%2Fc2%2F81f8c2d8bea55c7b77ba0c4446f2e6a1.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1669448134&t=67537dedc0f2afa9b410de555ea42fa1'}} style={styles.img}/>
<Image source={{uri: 'https://img1.baidu.com/it/u=3975477403,3704385503&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500'}} style={styles.img}/>
<Image source={{uri: 'https://img1.baidu.com/it/u=2949360167,1484933824&fm=253&fmt=auto&app=138&f=JPEG?w=772&h=500'}} style={styles.img}/>
</Swiper>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
swiper: {},
img: {
width: dimensions.width,
height: 200,
}
})
yarn add @react-native-community/geolocation
npm Install react-natlve-camera --save
yarn add react-native-image-picker
//组件
yarn add @react-navigation/native
yarn add react-natlve-reanimated
react-natlve-gesture-handler
react-native-screens
react-native-safe-area-context
@react-native-community/masked-view
@react-navigation/native-stack
import { View, Text, Button } from 'react-native'
import React from 'react'
import { createNativeStackNavigator } from '@react-navigation/native-stack';
// 页面不展示路由导航
export default function navNavigation() {
const Stack = createNativeStackNavigator();
function HomeScreen(prop:any) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button title='挑战新闻页面' onPress={() => prop.navigation.navigate('New')}></Button>
</View>
);
}
function NewScreen(prop:any) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button title='跳转到首页' onPress={() => prop.navigation.navigate('Home')}></Button>
</View>
);
}
return (
<Stack.Navigator
initialRouteName='New' // 默认加载页面
// screenOptions={{headerShown: false }} //隐藏头部路由
>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
title: '首页',
headerStyle: {
backgroundColor: 'red'
},
headerRight: () => {
return <Text>右侧展示</Text>
}
}}
/>
<Stack.Screen name="New" component={NewScreen} />
</Stack.Navigator>
)
}
import { View, Text, Button, TabBarIOSItem } from 'react-native'
import React from 'react'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
// 底部展示路由
export default function navNavigation() {
const Tab = createBottomTabNavigator();
function HomeScreen(prop:any) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
function NewScreen(prop:any) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
return (
<Tab.Navigator
initialRouteName='New' // 默认加载页面
// screenOptions={{headerShown: false }} //隐藏头部路由'
screenOptions={({route}) => ({
tabBarInactiveTintColor: "red",
tabBarActiveTintColor:'pink',
tabBarIcon:({focused, color, size}) => {
if(route.name === 'Home') {
return <Button title='首页' color={color}></Button>
}
return <Button title='新闻' color={color}></Button>
}
})}
>
<Tab.Screen
name="Home"
component={HomeScreen}
options={{
title: '首页',
headerStyle: {
backgroundColor: 'red'
},
headerRight: () => {
return <Text>右侧展示</Text>
}
}}
/>
<Tab.Screen name="New" component={NewScreen} />
</Tab.Navigator>
)
}
React-native-vector-icons