A flexible way to handle safe area, also works on Android and Web!
npm install react-native-safe-area-context
You then need to link the native parts of the library for the platforms you are using.
Linking the package is not required anymore with Autolinking.
iOS Platform:
$ npx pod-install
The easiest way to link the library is using the CLI tool by running this command from the root of your project:
react-native link react-native-safe-area-context
If you can't or don't want to use the CLI tool, you can also manually link the library using the instructions below (click on the arrow to show them):
Either follow the instructions in the React Native documentation to manually link the framework or link using Cocoapods by adding this to your Podfile
:
pod 'react-native-safe-area-context', :path => '../node_modules/react-native-safe-area-context'
Make the following changes:
android/settings.gradle
include ':react-native-safe-area-context'
project(':react-native-safe-area-context').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-safe-area-context/android')
android/app/build.gradle
dependencies {
...
implementation project(':react-native-safe-area-context')
}
android/app/src/main/.../MainApplication.java
On top, where imports are:
import com.th3rdwave.safeareacontext.SafeAreaContextPackage;
Add the SafeAreaContextPackage
class to your list of exported packages.
@Override
protected List<ReactPackage> getPackages() {
return Arrays.asList(
new MainReactPackage(),
...
new SafeAreaContextPackage()
);
}
NoteBefore 3.1.9 release of safe-area-context, Building for React Native 0.59 would not work due to missing header files. Use >= 3.1.9 to work around that.
This library has 2 important concepts, if you are familiar with React Context this is very similar.
The SafeAreaProvider component is a View
from where insets provided by Consumers are relative to. This means that if this view overlaps with any system elements (status bar, notches, etc.) these values will be provided to descendent consumers. Usually you will have one provider at the top of your app.
Consumers are components and hooks that allow using inset values provided by the nearest parent Provider. Values are always relative to a provider and not to these components.
SafeAreaView is the preferred way to consume insets. This is a regular View
with insets applied as extra padding or margin. It offers better performance by applying insets natively and avoids flickers that can happen with the other JS based consumers.
useSafeAreaInsets offers more flexibility, but can cause some layout flicker in certain cases. Use this if you need more control over how insets are applied.
You should add SafeAreaProvider
in your app root component. You may need to add it in other places like the root of modals and routes when using react-native-screens
.
Note that providers should not be inside a View
that is animated with Animated
or inside a ScrollView
since it can cause very frequent updates.
import { SafeAreaProvider } from 'react-native-safe-area-context';
function App() {
return <SafeAreaProvider>...</SafeAreaProvider>;
}
Accepts all View props. Has a default style of {flex: 1}
.
initialMetrics
Optional, defaults to null
.
Can be used to provide the initial value for frame and insets, this allows rendering immediatly. See optimization for more information on how to use this prop.
SafeAreaView
is a regular View
component with the safe area insets applied as padding or margin.
Padding or margin styles are added to the insets, for example style={{paddingTop: 10}}
on a SafeAreaView
that has insets of 20 will result in a top padding of 30.
import { SafeAreaView } from 'react-native-safe-area-context';
function SomeComponent() {
return (
<SafeAreaView style={{ flex: 1, backgroundColor: 'red' }}>
<View style={{ flex: 1, backgroundColor: 'blue' }} />
</SafeAreaView>
);
}
Accepts all View props.
edges
Optional, array of top
, right
, bottom
, and left
. Defaults to all.
Sets the edges to apply the safe area insets to.
For example if you don't want insets to apply to the top edge because the view does not touch the top of the screen you can use:
<SafeAreaView edges={['right', 'bottom', 'left']} />
mode
Optional, padding
(default) or margin
.
Apply the safe area to either the padding or the margin.
This can be useful for example to create a safe area aware separator component:
<SafeAreaView mode="margin" style={{ height: 1, backgroundColor: '#eee' }} />
Returns the safe area insets of the nearest provider. This allows manipulating the inset values from JavaScript. Note that insets are not updated synchronously so it might cause a slight delay for example when rotating the screen.
Object with { top: number, right: number, bottom: number, left: number }
.
import { useSafeAreaInsets } from 'react-native-safe-area-context';
function HookComponent() {
const insets = useSafeAreaInsets();
return <View style={{ paddingBottom: Math.max(insets.bottom, 16) }} />;
}
Returns the frame of the nearest provider. This can be used as an alternative to the Dimensions
module.
Object with { x: number, y: number, width: number, height: number }
SafeAreaInsetsContext
React Context with the value of the safe area insets.
Can be used with class components:
import { SafeAreaInsetsContext } from 'react-native-safe-area-context';
class ClassComponent extends React.Component {
render() {
return (
<SafeAreaInsetsContext.Consumer>
{(insets) => <View style={{ paddingTop: insets.top }} />}
</SafeAreaInsetsContext.Consumer>
);
}
}
withSafeAreaInsets
Higher order component that provides safe area insets as the insets
prop.
SafeAreaFrameContext
React Context with the value of the safe area frame.
initialWindowMetrics
Insets and frame of the window on initial render. This can be used with the initialMetrics
from SafeAreaProvider
. See optimization for more information.
Object with:
{
frame: { x: number, y: number, width: number, height: number },
insets: { top: number, left: number, right: number, bottom: number },
}
NOTE: This value can be null or out of date as it is computed when the native module is created.
Use useSafeAreaInsets
instead.
Use SafeAreaInsetsContext.Consumer
instead.
Use SafeAreaInsetsContext
instead.
Use initialWindowMetrics
instead.
If you are doing server side rendering on the web you can use initialMetrics
to inject insets and frame value based on the device the user has, or simply pass zero values. Since insets measurement is async it will break rendering your page content otherwise.
If you can, use SafeAreaView
. It's implemented natively so when rotating the device, there is no delay from the asynchronous bridge.
To speed up the initial render, you can import initialWindowMetrics
from this package and set as the initialMetrics
prop on the provider as described in Web SSR. You cannot do this if your provider remounts, or you are using react-native-navigation
.
import {
SafeAreaProvider,
initialWindowMetrics,
} from 'react-native-safe-area-context';
function App() {
return (
<SafeAreaProvider initialMetrics={initialWindowMetrics}>
...
</SafeAreaProvider>
);
}
This library includes a built in mock for Jest. It will use the following metrics by default:
{
frame: {
width: 320,
height: 640,
x: 0,
y: 0,
},
insets: {
left: 0,
right: 0,
bottom: 0,
top: 0,
},
}
To use it, add the following code to the jest setup file:
import mockSafeAreaContext from 'react-native-safe-area-context/jest/mock';
jest.mock('react-native-safe-area-context', () => mockSafeAreaContext);
To have more control over the test values it is also possible to pass initialMetrics
toSafeAreaProvider
to provide mock data for frame and insets.
export function TestSafeAreaProvider({ children }) {
return (
<SafeAreaProvider
initialMetrics={{
frame: { x: 0, y: 0, width: 0, height: 0 },
insets: { top: 0, left: 0, right: 0, bottom: 0 },
}}
>
{children}
</SafeAreaProvider>
);
}
See the Contributing Guide
1、如何使用react-navigation 1、安装依赖包 npm install --save react-native-gesture-handler react-native-reanimated react-native-screens react-navigation react-navigation-stack react-navigation-tabs 或是 yarn add r
1. react-native官网:简介 · React Native 中文网。 2. 配置window下环境:下载对应版本的node,python,Android Studio...,配置环境变量。参考《React Native环境配置搭建(史上最详细教程)》 3. 搭建项目: 全局安装react-native-cli脚手架:npm install -g react-native-cl。 创建j
1. 入门网站 https://reactnative.dev/docs/getting-started https://reactnative.cn/docs/getting-started 2. 更换npm国内源 a、临时使用 npm --registry https://registry.npm.taobao.org install express b、持久使用 npm config
1: FAILURE: Build failed with an exception. * What went wrong: Failed to capture snapshot of output files for task ':app:processDebugResources' property 'sourceOutputDir' during up-to-date check. > C
RN 使用react navigation的案例时运行pod-install报错 Auto-linking React Native modules for target `Entry_task_ts`: RNScreens and react-native-safe-area-context Analyzing dependencies Fetching podspec for `DoubleC
// 报错重要信息 Execution failed for task ':react-native-update:compileDebugNdk' 锁定module react-native-update, 在build.gradle中添加 android { sourceSets.main { jni.srcDirs = [] } } Sync grade
react-native 环境的搭建 全局安装 sudo npm i watchman react-native-cli -g 2.构建项目 react-native init +项目名 安装过程中勾选gem cocospods … 即可 3.启动项目 npm run ios react-navigation路由 环境搭建 实现路由跳转功能 1.在项目目录安装 npm install --s
如果你没有翻墙,第一次运行时多半时卡住了。 首先是一个.zip的下载包例如gradle-6.2-all.zip,这个包有点大,复制链接在迅雷下载。下载好后放在C:\Users\Justin.gradle\wrapper\dists\gradle-6.2-all.zip\xxxxxxxxxxxxxxx\,下 关闭运行再启动时会继续下载其它依赖,也许还是慢的无法运行,注意官方的这个解决办法: " 也可
本文向大家介绍react-native 启动React Native Packager,包括了react-native 启动React Native Packager的使用技巧和注意事项,需要的朋友参考一下 示例 在最新版本的React Native上,无需运行打包程序。它将自动运行。 默认情况下,这将在端口8081上启动服务器。要指定服务器所在的端口
百度移动统计SDK支持使用react native框架的H5页面统计,封装好的插件已经在github上开源,相关用法具体请参考:https://github.com/BaiduMobileAnalysis/baidumobstat-react-native。
The React Native environment has a lot of little quirks, so this documentation is aimed at helping smooth those over. Please feel free to create issues on GitHub for recommendations and additions to t
React Native 可以基于目前大热的开源JavaScript库React.js来开发iOS和Android原生App。而且React Native已经用于生产环境——Facebook Groups iOS 应用就是基于它开发的。 React Native的原理是在JavaScript中用React抽象操作系统原生的UI组件,代替DOM元素来渲染,比如以<View>取代<div>,以<Ima
本文向大家介绍react-native setState,包括了react-native setState的使用技巧和注意事项,需要的朋友参考一下 示例 要在应用程序中更改视图,可以使用setState-这将重新渲染您的组件及其任何子组件。setState在新状态和先前状态之间执行浅表合并,并触发组件的重新呈现。 setState 接受键值对象或返回键值对象的函数 键值对象 功能 使用函数对于基于
诸葛io移动统计支持React Native插件,以下为集成方法。 1. 环境准备 1.1. iOS环境 iOS 8.0+ 代码支持iOS8.0的系统 pod 1.0+ iOS系统的集成依赖于cocoaPod工具 1.2. Android环境 Android SDK 16+ 代码支持Android 16+ 1.3. React Native环境 react-native 0.50+ react-n