元素库
包含 React Navigation 中使用的 UI 元素和辅助程序的组件库。如果你正在构建自己的导航器,或者想要在应用中重用默认功能,它可能会很有用。
¥A component library containing the UI elements and helpers used in React Navigation. It can be useful if you're building your own navigator, or want to reuse a default functionality in your app.
安装
¥Installation
要使用此软件包,请确保你有 @react-navigation/native
及其依赖(遵循本指南),然后安装 @react-navigation/elements
:
¥To use this package, ensure that you have @react-navigation/native
and its dependencies (follow this guide), then install @react-navigation/elements
:
- npm
- Yarn
- pnpm
npm install @react-navigation/elements
yarn add @react-navigation/elements
pnpm add @react-navigation/elements
组件
¥Components
Header
可以用作标头的组件。默认情况下,所有导航器都使用它。
¥A component that can be used as a header. This is used by all the navigators by default.
用法:
¥Usage:
import { Header } from '@react-navigation/elements';
function MyHeader() {
return <Header title="My app" />;
}
要在导航器中使用标题,你可以在屏幕选项中使用 header
选项:
¥To use the header in a navigator, you can use the header
option in the screen options:
- Static
- Dynamic
import { Header, getHeaderTitle } from '@react-navigation/elements';
const MyStack = createNativeStackNavigator({
screenOptions: {
header: ({ options, route, back }) => (
<Header
{...options}
back={back}
title={getHeaderTitle(options, route.name)}
/>
),
},
screens: {
Home: HomeScreen,
},
});
import { Header, getHeaderTitle } from '@react-navigation/elements';
const Stack = createNativeStackNavigator();
function MyStack() {
return (
<Stack.Navigator
screenOptions={{
header: ({ options, route, back }) => (
<Header
{...options}
back={back}
title={getHeaderTitle(options, route.name)}
/>
),
}}
>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
);
}
这不会复制堆栈和原生堆栈导航器中标头的行为,因为堆栈导航器还包含动画,并且原生堆栈导航器标头由原生平台提供。
¥This doesn't replicate the behavior of the header in stack and native stack navigators as the stack navigator also includes animations, and the native stack navigator header is provided by the native platform.
它接受以下属性:
¥It accepts the following props:
headerTitle
字符串或返回要由标头使用的 React 元素的函数。默认为场景 title
。
¥String or a function that returns a React Element to be used by the header. Defaults to scene title
.
当指定一个函数时,它会收到一个包含以下属性的对象:
¥When a function is specified, it receives an object containing following properties:
-
allowFontScaling
:它是否缩放以尊重文本大小可访问性设置。¥
allowFontScaling
: Whether it scale to respect Text Size accessibility settings. -
tintColor
:标题的文本颜色。¥
tintColor
: Text color of the header title. -
style
:Text
组件的样式对象。¥
style
: Style object for theText
component. -
children
:标题字符串(来自options
中的title
)。¥
children
: The title string (fromtitle
inoptions
).
- Static
- Dynamic
const RootStack = createNativeStackNavigator({
screens: {
Home: {
screen: HomeScreen,
options: {
headerTitle: ({ allowFontScaling, tintColor, style, children }) => (
<Text
style={[style, { color: tintColor }]}
allowFontScaling={allowFontScaling}
>
{children}
</Text>
),
},
},
},
});
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
headerTitle: ({ allowFontScaling, tintColor, style, children }) => (
<Text
style={[style, { color: tintColor }]}
allowFontScaling={allowFontScaling}
>
{children}
</Text>
),
}}
/>
headerTitleAlign
如何对齐标题标题。可能的值:
¥How to align the header title. Possible values:
-
left
-
center
iOS 上默认为 center
,Android 上默认为 left
。
¥Defaults to center
on iOS and left
on Android.
headerTitleAllowFontScaling
标题标题字体是否应缩放以遵循文本大小辅助功能设置。默认为 false
。
¥Whether header title font should scale to respect Text Size accessibility settings. Defaults to false
.
headerLeft
返回一个 React 元素以显示在标题左侧的函数。
¥Function which returns a React Element to display on the left side of the header.
它接收一个包含以下属性的对象:
¥It receives an object containing following properties:
-
tintColor
:图标和标签的颜色。¥
tintColor
: The color of the icon and label. -
pressColor
:材质波纹的颜色(仅限 Android >= 5.0)。¥
pressColor
: The color of the material ripple (Android >= 5.0 only). -
pressOpacity
:按下按钮时的不透明度(Android < 5.0 和 iOS)。¥
pressOpacity
: The opacity of the button when it's pressed (Android < 5.0, and iOS). -
labelVisible
:标签文本是否可见。iOS 上默认为true
,Android 上默认为false
。¥
labelVisible
: Whether the label text is visible. Defaults totrue
on iOS andfalse
on Android. -
href
:在 Web 上按下按钮时要打开的 URL。¥
href
: The URL to open when the button is pressed on the Web.
你可以使用它来实现你的自定义左按钮,例如:
¥You can use it to implement your custom left button, for example:
- Static
- Dynamic
const RootStack = createNativeStackNavigator({
screens: {
Home: {
screen: HomeScreen,
options: {
headerLeft: (props) => (
<MyButton {...props} onPress={() => {
// Do something
}}>
)
}
}
}
})
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
headerLeft: (props) => (
<MyButton
{...props}
onPress={() => {
// Do something
}}
/>
),
}}
/>
headerRight
返回一个 React 元素以显示在标题右侧的函数。
¥Function which returns a React Element to display on the right side of the header.
它接收一个包含以下属性的对象:
¥It receives an object containing following properties:
-
tintColor
:图标和标签的颜色。¥
tintColor
: The color of the icon and label. -
pressColor
:材质波纹的颜色(仅限 Android >= 5.0)。¥
pressColor
: The color of the material ripple (Android >= 5.0 only). -
pressOpacity
:按下按钮时的不透明度(Android < 5.0 和 iOS)。¥
pressOpacity
: The opacity of the button when it's pressed (Android < 5.0, and iOS).
- Static
- Dynamic
const RootStack = createNativeStackNavigator({
screens: {
Home: {
screen: HomeScreen,
options: {
headerLeft: (props) => (
<MyButton {...props} onPress={() => {
// Do something
}}>
)
}
}
}
})
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
headerLeft: (props) => (
<MyButton
{...props}
onPress={() => {
// Do something
}}
/>
),
}}
/>
headerSearchBarOptions
标题中搜索栏的选项。指定此项后,标题将包含一个按钮以显示搜索输入。
¥Options for the search bar in the header. When this is specified, the header will contain a button to show a search input.
它可以包含以下属性:
¥It can contain the following properties:
-
autoCapitalize
:自动大写行为。可能的值:none
,words
,sentences
,characters
.¥
autoCapitalize
: The auto-capitalization behavior. Possible values:none
,words
,sentences
,characters
. -
autoFocus
:在安装时自动聚焦搜索输入。¥
autoFocus
: Automatically focus search input on mount. -
cancelButtonText
:用于代替默认Cancel
按钮文本的文本(仅限 iOS)。¥
cancelButtonText
: Text to be used instead of defaultCancel
button text (iOS only). -
inputType
:输入的类型。可能的值:text
,phone
,number
,email
.¥
inputType
: Type of the input. Possible values:text
,phone
,number
,email
. -
onBlur
:当搜索输入失去焦点时调用的回调。¥
onBlur
: Callback that gets called when search input has lost focus. -
onChangeText
:当文本更改时调用的回调。¥
onChangeText
: Callback that gets called when the text changes. -
onClose
:当搜索输入关闭时调用的回调。¥
onClose
: Callback that gets called when search input is closed. -
onFocus
:当搜索输入获得焦点时调用的回调。¥
onFocus
: Callback that gets called when search input has received focus. -
placeholder
:搜索输入为空时显示的文本。¥
placeholder
: Text displayed when search input is empty.
React.useLayoutEffect(() => {
navigation.setOptions({
headerSearchBarOptions: {
placeholder: 'Search',
onChangeText: (text) => {
// Do something
},
},
});
}, [navigation]);
headerShadowVisible
是否隐藏标题上的标高阴影 (Android) 或底部边框 (iOS)。
¥Whether to hide the elevation shadow (Android) or the bottom border (iOS) on the header.
这是以下样式的简写:
¥This is a short-hand for the following styles:
{
elevation: 0,
shadowOpacity: 0,
borderBottomWidth: 0,
}
如果上述样式在 headerStyle
中与 headerShadowVisible: false
一起指定,则 headerShadowVisible: false
优先。
¥If the above styles are specified in headerStyle
along with headerShadowVisible: false
, then headerShadowVisible: false
will take precedence.
headerStyle
标题的样式对象。例如,你可以在此处指定自定义背景颜色。
¥Style object for the header. You can specify a custom background color here, for example.
headerTitleStyle
标题组件的样式对象
¥Style object for the title component
headerLeftContainerStyle
自定义 headerLeft
组件容器的样式,例如添加填充。
¥Customize the style for the container of the headerLeft
component, for example to add padding.
headerRightContainerStyle
自定义 headerRight
组件容器的样式,例如添加填充。
¥Customize the style for the container of the headerRight
component, for example to add padding.
headerTitleContainerStyle
自定义 headerTitle
组件容器的样式,例如添加填充。
¥Customize the style for the container of the headerTitle
component, for example to add padding.
默认情况下,headerTitleContainerStyle
具有绝对位置样式并偏移 left
和 right
。如果使用自定义的 headerLeft
,这可能会导致 headerLeft
和 headerTitle
之间出现空白或重叠。可以通过调整 headerTitleContainerStyle
中的 left
和 right
样式以及 headerTitleStyle
中的 marginHorizontal
来解决。
¥By default, headerTitleContainerStyle
is with an absolute position style and offsets both left
and right
. This may lead to white space or overlap between headerLeft
and headerTitle
if a customized headerLeft
is used. It can be solved by adjusting left
and right
style in headerTitleContainerStyle
and marginHorizontal
in headerTitleStyle
.
headerBackgroundContainerStyle
headerBackground
元素容器的样式对象。
¥Style object for the container of the headerBackground
element.
headerTintColor
标题的色调颜色
¥Tint color for the header
headerPressColor
材质波纹的颜色(仅限 Android >= 5.0)
¥Color for material ripple (Android >= 5.0 only)
headerPressOpacity
按标题中按钮的不透明度(Android < 5.0 和 iOS)
¥Press opacity for the buttons in header (Android < 5.0, and iOS)
headerTransparent
默认为 false
。如果是 true
,标题将不会有背景,除非你明确提供 headerBackground
。标题也会浮动在屏幕上,以便与下面的内容重叠。
¥Defaults to false
. If true
, the header will not have a background unless you explicitly provide it with headerBackground
. The header will also float over the screen so that it overlaps the content underneath.
如果你想渲染半透明标题或模糊背景,这非常有用。
¥This is useful if you want to render a semi-transparent header or a blurred background.
请注意,如果你不希望内容显示在标题下方,则需要手动为内容添加上边距。React Navigation 不会自动执行此操作。
¥Note that if you don't want your content to appear under the header, you need to manually add a top margin to your content. React Navigation won't do it automatically.
要获取标题的高度,可以将 HeaderHeightContext
与 React 的上下文 API 或 useHeaderHeight
结合使用。
¥To get the height of the header, you can use HeaderHeightContext
with React's Context API or useHeaderHeight
.
headerBackground
返回一个 React 元素以渲染为标题背景的函数。这对于使用图片或渐变等背景非常有用。
¥Function which returns a React Element to render as the background of the header. This is useful for using backgrounds such as an image or a gradient.
例如,你可以将其与 headerTransparent
一起使用来渲染模糊视图以创建半透明标题。
¥For example, you can use this with headerTransparent
to render a blur view to create a translucent header.
- Static
- Dynamic
const Stack = createStackNavigator({
initialRouteName: 'Home',
screens: {
Home: {
screen: HomeScreen,
options: {
headerTransparent: true,
headerBackground: () => (
<BlurView
tint="dark"
intensity={100}
style={StyleSheet.absoluteFill}
/>
),
},
},
Profile: ProfileScreen,
},
});
import { BlurView } from 'expo-blur';
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
headerTransparent: true,
headerBackground: () => (
<BlurView
tint="dark"
intensity={100}
style={StyleSheet.absoluteFill}
/>
),
}}
/>
headerStatusBarHeight
在标题顶部添加额外的填充以考虑半透明状态栏。默认情况下,它使用设备安全区域插图中的最高值。传递 0 或自定义值以禁用默认行为并自定义高度。
¥Extra padding to add at the top of header to account for translucent status bar. By default, it uses the top value from the safe area insets of the device. Pass 0 or a custom value to disable the default behavior, and customize the height.
HeaderBackground
包含标题背景中使用的样式的组件,例如背景颜色和阴影。这是 headerBackground
的默认值。它接受与 View
相同的属性。
¥A component containing the styles used in the background of the header, such as the background color and shadow. It's the default for headerBackground
. It accepts the same props as a View
.
用法:
¥Usage:
<HeaderBackground style={{ backgroundColor: 'tomato' }} />
HeaderTitle
用于在标题中显示标题文本的组件。这是 headerTitle
的默认值。它接受与 Text
相同的属性。
¥A component used to show the title text in header. It's the default for headerTitle
. It accepts the same props as a Text
.
标题颜色默认为 主题文本颜色。你可以通过传递 tintColor
属性来覆盖它。
¥The color of title defaults to the theme text color. You can override it by passing a tintColor
prop.
用法:
¥Usage:
<HeaderTitle>Hello</HeaderTitle>
HeaderButton
一个用于在标题中显示按钮的组件。它可以用于左右按钮。它接受以下属性:
¥A component used to show a button in header. It can be used for both left and right buttons. It accepts the following props:
-
onPress
- 按下按钮时调用的回调。¥
onPress
- Callback to call when the button is pressed. -
href
- 用于网络上锚标记的href
。¥
href
- Thehref
to use for the anchor tag on web. -
disabled
- 布尔值,控制按钮是否被禁用。¥
disabled
- Boolean which controls whether the button is disabled. -
accessibilityLabel
- 屏幕阅读器按钮的辅助功能标签。¥
accessibilityLabel
- Accessibility label for the button for screen readers. -
testID
- 在测试中找到此按钮的 ID。¥
testID
- ID to locate this button in tests. -
tintColor
- 为标题按钮着色。¥
tintColor
- Tint color for the header button. -
pressColor
- 材质波纹的颜色(仅限 Android >= 5.0)。¥
pressColor
- Color for material ripple (Android >= 5.0 only). -
pressOpacity
- 如果平台不支持材料波纹,则按下按钮时的不透明度。¥
pressOpacity
- Opacity when the button is pressed if material ripple isn't supported by the platform. -
style
- 按钮的样式对象。¥
style
- Style object for the button. -
children
- 要为按钮渲染的内容。通常是图标。¥
children
- Content to render for the button. Usually the icon.
用法:
¥Usage:
<HeaderButton
accessibilityLabel="More options"
onPress={() => console.log('button pressed')}
>
<MaterialCommunityIcons
name="dots-horizontal-circle-outline"
size={24}
color={tintColor}
/>
</HeaderButton>
HeaderBackButton
用于显示后退按钮标题的组件。这是 堆栈导航器 中 headerLeft
的默认值。它接受以下属性:
¥A component used to show the back button header. It's the default for headerLeft
in the stack navigator. It accepts the following props:
-
disabled
- 控制按钮是否禁用的布尔值。¥
disabled
- Boolean which controls Whether the button is disabled. -
onPress
- 按下按钮时调用的回调。¥
onPress
- Callback to call when the button is pressed. -
pressColor
- 材质波纹的颜色(仅限 Android >= 5.0)。¥
pressColor
- Color for material ripple (Android >= 5.0 only). -
backImage
- 返回 React 元素以在标题的后退按钮中显示自定义图片的函数。¥
backImage
- Function which returns a React Element to display custom image in header's back button. -
tintColor
- 标题的色调颜色。¥
tintColor
- Tint color for the header. -
label
- 按钮的标签文本。通常是上一屏幕的标题。默认情况下,仅在 iOS 上显示。¥
label
- Label text for the button. Usually the title of the previous screen. By default, this is only shown on iOS. -
truncatedLabel
- 当没有足够的空间容纳完整标签时要显示的标签文本。¥
truncatedLabel
- Label text to show when there isn't enough space for the full label. -
labelVisible
- 标签文本是否可见。iOS 上默认为true
,Android 上默认为false
。¥
labelVisible
- Whether the label text is visible. Defaults totrue
on iOS andfalse
on Android. -
labelStyle
- 标签的样式对象。¥
labelStyle
- Style object for the label. -
allowFontScaling
- 标签字体是否应缩放以尊重文本大小辅助功能设置。¥
allowFontScaling
- Whether label font should scale to respect Text Size accessibility settings. -
onLabelLayout
- 当标签大小改变时触发的回调。¥
onLabelLayout
- Callback to trigger when the size of the label changes. -
screenLayout
- 屏幕布局。¥
screenLayout
- Layout of the screen. -
titleLayout
- 标题中标题元素的布局。¥
titleLayout
- Layout of the title element in the header. -
canGoBack
- 布尔值,指示是否可以在堆栈中导航回。¥
canGoBack
- Boolean to indicate whether it's possible to navigate back in stack. -
accessibilityLabel
- 屏幕阅读器按钮的辅助功能标签。¥
accessibilityLabel
- Accessibility label for the button for screen readers. -
testID
- 在测试中找到此按钮的 ID。¥
testID
- ID to locate this button in tests. -
style
- 按钮的样式对象。¥
style
- Style object for the button.
用法:
¥Usage:
<HeaderBackButton label="Hello" onPress={() => console.log('back pressed')} />
MissingIcon
渲染缺失图标符号的组件。它可以用作图标的后备,以显示缺少图标。它接受以下属性:
¥A component that renders a missing icon symbol. It can be used as a fallback for icons to show that there's a missing icon. It accepts the following props:
-
color
- 图标的颜色。¥
color
- Color of the icon. -
size
- 图标的大小。¥
size
- Size of the icon. -
style
- 图标的附加样式。¥
style
- Additional styles for the icon.
PlatformPressable
一个在 Pressable
之上提供抽象以处理平台差异的组件。除了 Pressable
的属性外,它还接受以下附加属性:
¥A component which provides an abstraction on top of Pressable
to handle platform differences. In addition to Pressable
's props, it accepts following additional props:
-
pressColor
- Android 上的材质颜色在按下时会出现波纹¥
pressColor
- Color of material ripple on Android when it's pressed -
pressOpacity
- 如果平台不支持材质波纹,则按下时的不透明度¥
pressOpacity
- Opacity when it's pressed if material ripple isn't supported by the platform
Button
一个渲染按钮的组件。除了 PlatformPressable
的属性外,它还接受以下附加属性:
¥A component that renders a button. In addition to PlatformPressable
's props, it accepts following additional props:
-
variant
- 按钮的变体。可能的值为:¥
variant
- Variant of the button. Possible values are:-
tinted
(默认)¥
tinted
(default) -
plain
-
filled
-
-
color
- 按钮的颜色。默认为 theme 的主颜色。¥
color
- Color of the button. Defaults to the theme's primary color. -
children
- 要在按钮内渲染的内容。¥
children
- Content to render inside the button.
此外,按钮与 React Navigation 集成并接受与 useLinkProps
hook 相同的 props。
¥In addition, the button integrates with React Navigation and accepts the same props as useLinkProps
hook.
它可用于通过指定屏幕名称和参数在屏幕之间导航:
¥It can be used to navigate between screens by specifying a screen name and params:
<Button screen="Profile" params={{ userId: 'jane' }}>
Go to Profile
</Button>
或作为常规按钮:
¥Or as a regular button:
<Button onPress={() => console.log('button pressed')}>Press me</Button>
Label
Label
组件用于渲染小文本。它在 底部选项卡导航器 中用于渲染每个选项卡的标签。
¥The Label
component is used to render small text. It is used in Bottom Tab Navigator to render the label for each tab.
除了标准 Text
属性外,它还接受以下属性:
¥In addition to the standard Text
props, it accepts the following props:
-
tintColor
- 标签的颜色。默认为 theme 的文本颜色。¥
tintColor
- Color of the label. Defaults to the theme's text color.
用法:
¥Usage:
<Label>Home</Label>
ResourceSavingView
该组件通过利用 removeClippedSubviews
来帮助提高非活动屏幕的性能。它接受 visible
属性来指示是否应剪切屏幕。
¥A component which aids in improving performance for inactive screens by utilizing removeClippedSubviews
. It accepts a visible
prop to indicate whether a screen should be clipped.
用法:
¥Usage:
<ResourceSavingView visible={0}>{/* Content */}</ResourceSavingView>
实用工具
¥Utilities
SafeAreaProviderCompat
[react-native-safe-area-context](https://github.com/th3rdwave/react-native-safe-area-context) 的
SafeAreaProvider` 组件的封装,其中包括初始值。
¥A wrapper over the SafeAreaProvider
component from `react-native-safe-area-context which includes initial values.
用法:
¥Usage:
<SafeAreaProviderCompat>{/* Your components */}</SafeAreaProviderCompat>
HeaderBackContext
可用于获取父屏幕的后标题的 React 上下文。
¥React context that can be used to get the back title of the parent screen.
import { HeaderBackContext } from '@react-navigation/elements';
// ...
<HeaderBackContext.Consumer>
{(headerBack) => {
if (headerBack) {
const backTitle = headerBack.title;
/* render something */
}
/* render something */
}}
</HeaderBackContext.Consumer>;
HeaderShownContext
React 上下文可用于检查标题在父屏幕中是否可见。
¥React context that can be used to check if a header is visible in a parent screen.
import { HeaderShownContext } from '@react-navigation/elements';
// ...
<HeaderShownContext.Consumer>
{(headerShown) => {
/* render something */
}}
</HeaderShownContext.Consumer>;
HeaderHeightContext
React 上下文可用于获取父屏幕中最近的可见标题的高度。
¥React context that can be used to get the height of the nearest visible header in a parent screen.
import { HeaderHeightContext } from '@react-navigation/elements';
// ...
<HeaderHeightContext.Consumer>
{(headerHeight) => {
/* render something */
}}
</HeaderHeightContext.Consumer>;
useHeaderHeight
返回父屏幕中最近的可见标题高度的钩子。
¥Hook that returns the height of the nearest visible header in the parent screen.
import { useHeaderHeight } from '@react-navigation/elements';
// ...
const headerHeight = useHeaderHeight();
getDefaultHeaderHeight
返回默认标题高度的助手。它需要以下参数:
¥Helper that returns the default header height. It takes the following parameters:
-
layout
- 屏幕布局,即包含height
和width
属性的对象。¥
layout
- Layout of the screen, i.e. an object containingheight
andwidth
properties. -
statusBarHeight
- 状态栏的高度¥
statusBarHeight
- height of the statusbar
getHeaderTitle
返回要在标题中使用的标题文本的辅助程序。它需要以下参数:
¥Helper that returns the title text to use in header. It takes the following parameters:
-
options
- 屏幕的选项对象。¥
options
- The options object of the screen. -
fallback
- 如果在选项中找不到标题,则后备标题字符串。¥
fallback
- Fallback title string if no title was found in options.