import SQLite from "react-native-sqlite-2";
 
// 创建或打开数据库
const dbPath = SQLite.openDatabase({ name: "myDatabase.db" });
 
// 创建表
dbPath.transaction((tx) => {
  tx.executeSql(
    'CREATE TABLE IF NOT EXISTS People (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
    [],
    () => console.log("Table created"),
    (error) => console.error("Error creating table: ", error)
  );
});
 
// 插入数据
dbPath.transaction((tx) => {
  tx.executeSql(
    'INSERT INTO People (name, age) VALUES (?, ?)',
    ['Alice', 30],
    () => console.log("Row inserted"),
    (error) => console.error("Error inserting row: ", error)
  );
});
 
// 查询数据
dbPath.transaction((tx) => {
  tx.executeSql(
    'SELECT * FROM People',
    [],
    (_, { rows: { _array } }) => console.log("Rows selected: ", _array),
    (error) => console.error("Error selecting row: ", error)
  );
});
 
// 更新数据
dbPath.transaction((tx) => {
  tx.executeSql(
    'UPDATE People SET age = ? WHERE name = ?',
    [31, 'Alice'],
    () => console.log("Row updated"),
    (error) => console.error("Error updating row: ", error)
  );
});
 
// 删除数据
dbPath.transaction((tx) => {
  tx.executeSql(
    'DELETE FROM People WHERE name = ?',
    ['Alice'],
    () => console.log("Row deleted"),
    (error) => console.error("Error deleting row: ", error)
  );
});

这段代码展示了如何在React Native项目中使用react-native-sqlite-2库来进行SQLite数据库的基本操作,包括创建表、插入数据、查询数据、更新数据和删除数据。这对于需要在移动应用中集成数据库功能的开发者来说是一个很好的学习资源。




import React, { useState, useEffect, useCallback } from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
 
const ItemSeparatorComponent = () => (
  <View
    style={{
      height: 1,
      width: "100%",
      backgroundColor: "#ccc",
    }}
  />
);
 
const ListFooterComponent = ({ isLoading }) => {
  if (isLoading) {
    return (
      <View
        style={{
          paddingVertical: 20,
          borderTopWidth: 1,
          borderColor: "#ccc"
        }}
      >
        <ActivityIndicator />
      </View>
    );
  }
  return null;
};
 
const App = () => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
 
  const fetchData = useCallback(async () => {
    if (isLoading) return;
    setIsLoading(true);
 
    try {
      const response = await fetch(
        `https://api.example.com/data?page=${page}`
      );
      const newData = await response.json();
      setData(page === 1 ? newData : [...data, ...newData]);
      setPage(page + 1);
    } catch (error) {
      console.error(error);
    }
 
    setIsLoading(false);
  }, [isLoading, page, data]);
 
  useEffect(() => {
    fetchData();
  }, [fetchData]);
 
  const handleRefresh = useCallback(async () => {
    if (isRefreshing) return;
    setIsRefreshing(true);
    setPage(1);
    setData([]);
    await fetchData();
    setIsRefreshing(false);
  }, [fetchData, isRefreshing]);
 
  return (
    <FlatList
      data={data}
      onEndReached={fetchData}
      onEndReachedThreshold={0.5}
      onRefresh={handleRefresh}
      refreshing={isRefreshing}
      keyExtractor={item => item.id}
      renderItem={({ item }) => (
        <View>
          <Text>{item.title}</Text>
        </View>
      )}
      ItemSeparatorComponent={ItemSeparatorComponent}
      ListFooterComponent={
        <ListFooterComponent isLoading={isLoading} />
      }
    />
  );
};
 
export default App;

这段代码展示了如何使用React Native的FlatList组件来实现一个基本的分页列表。它使用了useState和useEffect来管理组件的状态,并通过useCallback来避免不必要的重渲染。代码中包含了分页加载数据、下拉刷新,以及加载指示器的例子,是一个很好的学习和实践React Native列表分页的例子。




import React, { useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import AMapLocation from 'react-native-amap-location';
 
const App = () => {
  const [location, setLocation] = useState(null);
 
  useEffect(() => {
    AMapLocation.getCurrentPosition({
      desiredAccuracy: AMapLocation.Accuracy.Hight,
      locatingWithReGeocode: true,
    }).then((location) => {
      setLocation(location);
    }).catch((error) => {
      console.error('Error fetching location: ', error);
    });
  }, []);
 
  if (!location) {
    return (
      <View>
        <Text>正在获取位置信息...</Text>
      </View>
    );
  }
 
  return (
    <View>
      <Text>纬度: {location.latitude}</Text>
      <Text>经度: {location.longitude}</Text>
      <Text>地址: {location.address}</Text>
    </View>
  );
};
 
export default App;

这段代码使用React Native和react-native-amap-location库获取当前位置信息,并展示在屏幕上。它首先检查是否有位置信息,如果没有,它将通过AMapLocation获取位置并更新状态。然后,它根据位置信息渲染屏幕。这个例子展示了如何在React Native应用中使用高级的定位服务。




import React from 'react';
import { Text, View } from 'react-native';
 
export default class App extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Hello, Cross-Platform World!</Text>
      </View>
    );
  }
}

这段代码展示了如何使用React Native创建一个简单的跨平台移动应用,它将在iOS和Android上共享相同的UI和用户体验。代码中使用了React组件的ES6类语法,并导入了React Native的核心组件TextView,这是构建用户界面的基本元素。在render方法中,我们返回一个简单的视图,它在屏幕中居中显示文本。这个例子是学习如何开始使用React Native的一个很好的起点。




import React, { useState } from 'react';
import { View, Image, StyleSheet, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
 
const ImageZoom = ({ image }) => {
  const [isZoomed, setIsZoomed] = useState(false);
 
  const toggleZoom = () => {
    setIsZoomed(!isZoomed);
  };
 
  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={toggleZoom}>
        <Image style={isZoomed ? styles.zoomedImage : styles.image} source={{ uri: image }} />
      </TouchableOpacity>
      {isZoomed && (
        <View style={styles.zoomControls}>
          <Icon name="zoom-out" size={30} color="white" onPress={toggleZoom} />
        </View>
      )}
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    width: 300,
    height: 200,
    resizeMode: 'contain',
  },
  zoomedImage: {
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
  },
  zoomControls: {
    position: 'absolute',
    bottom: 20,
    right: 20,
    zIndex: 100,
  },
});
 
export default ImageZoom;

这个代码示例展示了如何在React Native应用中创建一个图片缩放组件。它使用了TouchableOpacity来包裹Image组件,并允许用户点击图片进行缩放。同时,它还包括了一个简单的缩放控制按钮,允许用户返回正常大小的视图。这个示例简洁明了,并且使用了React Hooks来管理组件状态,这是React Native中推荐的做法。

在2023年,以下是一些最受欢迎的Flutter和React Native UI库:

Flutter:

  1. Google的Material Design (默认)
  2. Google的Cupertino (iOS风格)
  3. Firebase的FlutterFire (用于集成Firebase服务)
  4. GetX (用于状态管理和路由管理)
  5. Flutter Simple Dialog (简单对话框)
  6. Flutter Slider (滑块)
  7. Flutter Staggered Grid View (栅格视图)
  8. Flutter SVG (用于SVG图像的支持)
  9. Flutter Tab View (标签页)
  10. Flutter Toast (弹出式提示)

React Native:

  1. React Native Paper (Material Design)
  2. React Native Elements (更多样式的UI组件)
  3. React Native Vector Icons (图标)
  4. React Native Animateable (动画)
  5. React Native Gesture Handler (手势)
  6. React Native Reanimated (动画和手势)
  7. React Native Safe Area Context (安全区域)
  8. React Native Screens (更流畅的屏幕导航)
  9. React Native Vector Icons (矢量图标)
  10. React Native WebView (网页视图)

请注意,这些库的流行度可能会随着时间和社区需求的变化而变化。始终建议检查官方文档以获取最新和最全面的信息。




import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import TreeSelect from 'react-native-tree-select';
 
const data = [
  {
    label: 'Node 1',
    value: 'node1',
    children: [
      { label: 'Child 1', value: 'child1' },
      { label: 'Child 2', value: 'child2' }
    ]
  },
  {
    label: 'Node 2',
    value: 'node2'
  }
];
 
const TreeSelectExample = () => {
  const [selectedValue, setSelectedValue] = React.useState(null);
 
  return (
    <View style={styles.container}>
      <TreeSelect
        data={data}
        value={selectedValue}
        onChange={setSelectedValue}
        style={styles.treeSelect}
      />
      <View style={styles.selectedContainer}>
        <Text>Selected Value: {selectedValue}</Text>
      </View>
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20
  },
  treeSelect: {
    width: '100%',
    height: 300
  },
  selectedContainer: {
    marginTop: 20,
    padding: 10,
    backgroundColor: '#ddd'
  }
});
 
export default TreeSelectExample;

这个代码示例展示了如何在React Native应用中使用react-native-tree-select库来创建一个多级选择器。代码中定义了一个简单的树状数据结构,并使用TreeSelect组件来渲染它。用户可以选择任何节点,选择的值会实时更新并显示在屏幕上方的文本组件中。




import React from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
 
const App = () => {
  return (
    <View style={styles.container}>
      <Image source={{ uri: 'https://example.com/poster.jpg' }} style={styles.poster} />
      <View style={styles.details}>
        <Text style={styles.title}>电影标题</Text>
        <Text style={styles.rating}>9.5/10</Text>
        <Text style={styles.description}>
          一个关于某个主题的电影描述...
        </Text>
      </View>
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    padding: 10
  },
  poster: {
    width: 150,
    height: 200,
    marginRight: 10
  },
  details: {
    flex: 1
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold'
  },
  rating: {
    fontSize: 16,
    color: '#009688'
  },
  description: {
    fontSize: 14,
    color: '#777',
    marginTop: 5
  }
});
 
export default App;

这段代码展示了如何使用React Native的基本组件来创建一个简单的电影海报组件,其中包含了一个海报图片和电影的详细信息。样式使用了flexbox布局来实现响应式设计,确保在不同尺寸的屏幕上都有良好的显示效果。




import React from 'react';
import { View } from 'react-native';
import { TextField } from 'react-native-material-textfield';
 
export default class MyForm extends React.Component {
  state = {
    username: '',
    password: ''
  };
 
  handleUsernameChange = (username) => {
    this.setState({ username });
  };
 
  handlePasswordChange = (password) => {
    this.setState({ password });
  };
 
  render() {
    return (
      <View>
        <TextField
          label="用户名"
          value={this.state.username}
          onChangeText={this.handleUsernameChange}
        />
        <TextField
          label="密码"
          value={this.state.password}
          onChangeText={this.handlePasswordChange}
          secureTextEntry={true} // 设置密码字段为密文显示
        />
      </View>
    );
  }
}

这段代码展示了如何在React Native应用中使用react-native-material-textfield库来创建一个用户名和密码的登录表单。代码中使用了TextField组件,并通过state管理输入的状态,以确保用户的输入能够被组件内部的处理函数捕获和更新。

在React Native中,Alert.alert是一个用于显示一个带有标题、信息、取消按钮以及一些可选操作按钮的警告弹窗的API。这个弹窗会在iOS和Android上显示为一个本地化的模态窗口。

以下是一个使用Alert.alert的基本示例:




import React, { Component } from 'react';
import { Alert, Button } from 'react-native';
 
export default class AlertExample extends Component {
  showAlert = () => {
    Alert.alert(
      '标题',
      '这是一个简单的警告弹窗',
      [
        {
          text: '取消',
          onPress: () => console.log('取消按钮被点击'),
          style: 'cancel',
        },
        { text: '确定', onPress: () => console.log('确定按钮被点击') },
      ],
      { cancelable: false }
    );
  };
 
  render() {
    return (
      <Button title="显示警告" onPress={this.showAlert} />
    );
  }
}

在这个例子中,当按钮被按下时,showAlert函数会被调用,它创建并显示一个包含标题、信息以及两个按钮的警告弹窗。其中一个按钮设置了style: 'cancel',这表示它是一个取消按钮,它不会执行任何操作,只是关闭弹窗。另一个按钮是一个普通的操作按钮,点击会在控制台输出一条信息。cancelable选项被设置为false,这意味着用户不能通过点击背景或使用物理按键来取消弹窗。