# Ant Design Mobile RN Component Documentation Aggregated content from all component docs. > 47 components ## Accordion Source: https://rn.mobile.ant.design/components/accordion.md # Accordion > This package has been deprecated in `5.2.1`, recommend [components/Collapse](/components/collapse) You can collapse / expand the content area. ### Rules - Group and hide complex areas. - Typically, only a single content area is allowed to expand at a time; in special cases, multiple content areas can be expanded at the same time. ## Examples ```tsx import { Accordion, List } from '@ant-design/react-native' import React from 'react' import { View } from 'react-native' export default class AccordionExmple extends React.Component { state = { activeSections: [2, 0], } onChange = (activeSections: number[]) => { this.setState({ activeSections }) } render() { return ( Content 1 Content 2 Content 3 this is panel content2 or other Text text text text text text text text text text text text text text text ) } } ``` ## API ### Accordion | Properties | Descrition | Type | Default | | ----------------- | ------------------------------------------------------------------------------------------------ | ------------------------- | ------- | | onChange(indexes) | A function that is called when the currently active section(s) are updated. | (indexes: number[])=>void | - | | activeSections | Control which indices in the `sections` array are currently open. If empty, closes all sections. | number[] | [] | Read more https://github.com/oblador/react-native-collapsible#properties-1 ### Accordion.Panel | Properties | Descrition | Type | Default | | ---------- | ----------------------- | ----------------------- | ------- | | key | corresponding activeKey | String | - | | header | header content of Panel | React.Element or String | - | Note: Currently does not support nested use for RN. --- ## ActionSheet Source: https://rn.mobile.ant.design/components/action-sheet.md # ActionSheet The modal box pops up from the bottom, providing more than two actions related to the current scene, and also support provide the title and description. Built-in fixed display style, does not support particularly flexible changes. ### Rules - Provide a clear exit button. - Can highlight the destructive operation, e.g. "delete" use red text. - Do not place too much content to avoid vertical roll of the panel. ## Examples ```tsx import { ActionSheet, Button, Provider } from '@ant-design/react-native' import React from 'react' import { Platform, Text, View } from 'react-native' export default class Test extends React.Component { constructor(props: any) { super(props) this.state = { clicked: 'none', text: '', } } render() { return ( clicked button: {this.state.clicked} {this.state.text} ) } showActionSheet = () => { const BUTTONS = [ 'Operation1', 'Operation2', 'Operation3', 'Delete', 'Cancel', ] ActionSheet.showActionSheetWithOptions( { title: 'Title', message: 'Description', options: BUTTONS, cancelButtonIndex: 4, destructiveButtonIndex: 3, }, (buttonIndex: any) => { this.setState({ clicked: BUTTONS[buttonIndex] }) }, ) } showShareActionSheet = () => { const opts: any = { message: 'Message to go with the shared url', title: 'Share Actionsheet', } if (Platform.OS === 'ios') { opts.url = 'https://www.alipay.com/' opts.tintColor = '#ff0000' opts.excludedActivityTypes = ['com.apple.UIKit.activity.PostToTwitter'] } ActionSheet.showShareActionSheetWithOptions( opts, (error: any) => alert(error), (success: any, method: any) => { let text if (success) { text = `Shared with ${method}` } else { text = 'Did not share' } this.setState({ text }) }, ) } } export const title = 'ActionSheet' export const description = 'ActionSheet example' ``` ## API ### ActionSheet.showActionSheetWithOptions(options, callback) Properties | Descrition | Type | Default ----|-----|------|------ | options | ActionSheet's options | Object | - | | callback | Callback for selected item | (index:number):void | - | Display a action sheet. The `options` object must contain one or more of: Properties | Descrition | Type | Default ----|-----|------|------ | options | a list of button titles (required) | Array or String | - | | cancelButtonIndex | index of cancel button in `options` | Number | - | | destructiveButtonIndex | index of destructive button in `options` | Number | - | | title | a title to show above the action sheet | String | - | | message | a message to show below the title | String or React.element | - | ### ActionSheet.showShareActionSheetWithOptions(options, failureCallback?, successCallback?) `React-Native Only, react-native@version >= 0.39` Properties | Descrition | Type | Default ----|-----|------|------ | options | ShareActionSheet's options | Object | - | | failureCallback | Callback for share failed(`iOS Only`, See [react-native/share](https://github.com/facebook/react-native/blob/master/Libraries/Share/Share.js#L80) ) | (error):void | - | | successCallback | Callback for share successed(`iOS Only`, See [react-native/share](https://github.com/facebook/react-native/blob/master/Libraries/Share/Share.js#L80) ) | (completed:Boolean, activityType?:String):void | - | Display a shareable action sheet. The `options` object must contain one or more of: Properties | Descrition | Type | Default ----|-----|------|------ | message | a message to share | String | - | | title | title of the message | String | - | | url | an URL to share `iOS Only` | String | - | | excludedActivityTypes | the activities to exclude from the ShareActionSheet `iOS Only` | Array | - | ### ActionSheet.close() Close the action sheet.`Android Only` --- ## ActivityIndicator Source: https://rn.mobile.ant.design/components/activity-indicator.md # ActivityIndicator `ActivityIndicator` indicates that a task is currently in progress. ### Rules - Don't stop activity indicator if the task is not completed. - By providing meaningful texts under certain circumstances can help user understand which task is in progress. eg: uploading photos. - If you know the user's waiting time, you can use `Progress` instead. ## Examples ```tsx import { ActivityIndicator, Button, Flex, WhiteSpace, WingBlank } from '@ant-design/react-native' import React from 'react' import { StyleSheet, Text, View } from 'react-native' export default class ActivityIndicatorExample extends React.Component< any, any > { closeTimer: any constructor(props: any) { super(props) this.state = { animating: false, } this.loadingToast = this.loadingToast.bind(this) } componentWillUnmount() { clearTimeout(this.closeTimer) } loadingToast() { this.setState({ animating: !this.state.animating }) this.closeTimer = setTimeout(() => { this.setState({ animating: !this.state.animating }) }, 2000) } render() { return ( Icon without text Icon with text Dark Background Large Size ) } } const styles = StyleSheet.create({ demo: { marginTop: 20, }, darkBg: { alignItems: 'center', justifyContent: 'center', width: 89, height: 89, backgroundColor: '#2B2F42', }, gray: { backgroundColor: '#CCC', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, }) ``` ## API ```jsx ``` ### ActivityIndicator Properties | Descrition | Type | Default -----------|------------|------|-------- | animating | Whether to show the indicator (true, the default) or hide it (false). | boolean | true | | size | Size of the indicator (`small`/`large` or number [android only]) | string\|number | small | | toast | Whether to use toast style | boolean | false | | text | loading text behind the indicator | string | - | | color | The foreground color of the spinner (default is gray). | string | gray | --- ## Badge Source: https://rn.mobile.ant.design/components/badge.md # Badge The red dot at corner for notification and getting user attention. ### When to use - Use plain dot badge when user just need to know there is something new, eg: one-to-one new messages. - Use numberic badge when user need to know specific number of notifications, eg: new messages from a group. ## Examples ```tsx import { Badge, WhiteSpace } from '@ant-design/react-native' import React from 'react' import { ScrollView, View } from 'react-native' export default class BasicTagExample extends React.Component { render() { return ( ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- size | size of badge, optional: `large` `small` | string | `small` text | text or number inside badge | string\|number | - corner | whether is badge at corner position | boolean | `false` dot | show badge as a red dot | boolean | `false` overflowCount | max count to show | number | `99` --- ## Button Source: https://rn.mobile.ant.design/components/button.md # Button To trigger an operation. ## Examples ```tsx import { Button, Icon, WhiteSpace, WingBlank } from '@ant-design/react-native' import React from 'react' export default () => ( ) ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | type | can be set to `primary`/`ghost`/`warning` or omitted | string | - | | size | can be set to `large`、`small` or omitted | string | `large`| | activeStyle | the feedback's custom style (set to false to disable click feedback) | {}/false | {} | | activeClassName | the feedback's custom class name | string | | | disabled | set disabled | boolean | false | | onPress | set the handler to handle `click` event | (e: Object): void | - | | style | custom style | Object | - | | styles | Semantic DOM style | [ButtonStyles](#buttonStyles-interface) | - | | onPressIn | same as RN Pressable onPressIn | (e: Object): void | - | | onPressOut | same as RN Pressable onPressOut | (e: Object): void | - | | onShowUnderlay | same as RN Pressable onPressIn but only triggered if `activeStyle` is not false | (e: Object): void | - | | onHideUnderlay | same as RN Pressable onPressOut but only triggered if `activeStyle` is not false | (e: Object): void | - | ### ButtonStyles interface ```typescript interface ButtonStyles { container: ViewStyle defaultHighlight: ViewStyle primaryHighlight: ViewStyle ghostHighlight: ViewStyle warningHighlight: ViewStyle wrapperStyle: ViewStyle underlayStyle: ViewStyle largeRaw: ViewStyle largeUnderlayContainerRaw: ViewStyle smallRaw: ViewStyle smallUnderlayContainerRaw: ViewStyle defaultRaw: ViewStyle defaultUnderlayContainerRaw: ViewStyle primaryRaw: ViewStyle primaryUnderlayContainerRaw: ViewStyle ghostRaw: ViewStyle ghostUnderlayContainerRaw: ViewStyle warningRaw: ViewStyle warningUnderlayContainerRaw: ViewStyle defaultDisabledRaw: ViewStyle primaryDisabledRaw: ViewStyle ghostDisabledRaw: ViewStyle warningDisabledRaw: ViewStyle defaultHighlightText: TextStyle primaryHighlightText: TextStyle ghostHighlightText: TextStyle warningHighlightText: TextStyle rawText: TextStyle largeRawText: TextStyle smallRawText: TextStyle defaultRawText: TextStyle primaryRawText: TextStyle ghostRawText: TextStyle warningRawText: TextStyle defaultDisabledRawText: TextStyle primaryDisabledRawText: TextStyle ghostDisabledRawText: TextStyle warningDisabledRawText: TextStyle indicator: ViewStyle } ``` --- ## Card Source: https://rn.mobile.ant.design/components/card.md # Card Card can be used to organize information and operations, usually also as an entry for detailed information. ### Rules - The shape is rectangular. - The content can consist of multiple elements of varying type, eg: images, texts, buttons, etc. ## Examples ```tsx import { Card, WhiteSpace, WingBlank } from '@ant-design/react-native' import React from 'react' import { Text, View } from 'react-native' export default class BasicCardExample extends React.Component { render() { return ( Card Content Card Content ) } } ``` ## API ### Card Properties | Descrition | Type | Default -----------|------------|------|-------- | full | whether is full column | boolean | `false` | ### Card.Header Properties | Descrition | Type | Default -----------|------------|------|-------- |title| title for `Card.Header` | React.Element、String | | |thumb| thumb to render in the left of `Card.Header` | String、React.Element | | |thumbStyle| style of thumb | Object | {} | |extra| extra content to render in the right of `Card.Header` | React.Element、String | | ### Card.Body Properties | Descrition | Type | Default -----------|------------|------|-------- | | | | | ### Card.Footer Properties | Descrition | Type | Default -----------|------------|------|-------- |content| content of `Card.Footer` | React.Element、String | | |extra| extra content of `Card.Footer` | React.Element、String | | --- ## Carousel Source: https://rn.mobile.ant.design/components/carousel.md # Carousel ## Examples ```tsx import { Button, Carousel } from '@ant-design/react-native' import React from 'react' import { ScrollView, StyleSheet, Text, TextStyle, View, ViewStyle, } from 'react-native' export default class BasicCarouselExample extends React.Component { carousel: null | Carousel constructor(props: any) { super(props) this.state = { selectedIndex: 2, autoplay: true, } } onHorizontalSelectedIndexChange = (index: number) => { /* tslint:disable: no-console */ console.log('horizontal change to', index) this.setState({ selectedIndex: index }) } onVerticalSelectedIndexChange(index: number) { /* tslint:disable: no-console */ console.log('vertical change to', index) } render() { return ( horizontal (this.carousel = ref)}> Carousel 1 Carousel 2 Carousel 3 Carousel 4 Carousel 5 vertical Carousel 1 Carousel 2 Carousel 3 Carousel 4 Carousel 5 ) } } const styles = StyleSheet.create<{ wrapper: ViewStyle containerHorizontal: ViewStyle containerVertical: ViewStyle text: TextStyle }>({ wrapper: { backgroundColor: '#fff', width: '100%', height: 150, }, containerHorizontal: { flexGrow: 1, alignItems: 'center', justifyContent: 'center', }, containerVertical: { flexGrow: 1, alignItems: 'center', justifyContent: 'center', }, text: { color: '#fff', fontSize: 36, }, }) ``` ## API Properties | Descrition | Type | Default | Version -----------|------------|------|---------|---------- | afterChange | callback to be called after a slide is changed | (current: number) => void | | | | autoplay | autoplay mode active | Boolean | false | | | autoplayInterval | interval for autoplay iteration | Number | 3000 | | | dots | whether to display the indication dots | Boolean | true | | | dotStyle | style of dots | ViewStyle | | | | dotActiveStyle | style of active dot | ViewStyle | | | | infinite | whether is infinite loop | Boolean | false | | | lazy | Function which takes an object with the current page and returns a boolean to indicate whether to lazily render the scenes. | Boolean \| `(index:number) => boolean` | false | `5.3.1` | | renderLazyPlaceholder | A callback that returns a custom React Element to render for pages not yet rendered. Requires the `lazy` prop to be enabled. | `(index:number) => ReactNode` | - | `5.3.1` | | pageStyle | style of the carousel page | ViewStyle | | | | pagination | A generator function which could be used to customized pagination. | (props) => ReactNode | | | | selectedIndex | current selected index | number | 0 | | | style | ScrollView style
(`tips: Recommended setting, the overall carousel size is determined by the container scrollview and not the inner page`) | ViewStyle | | | | vertical | controls the pagination display direction. | Boolean | false | | | onScrollAnimationEnd | Called when a scrolling animation ends. | ()=>void | | `5.3.0` | The rest of the props of Carousel are exactly the same as the react-native [ScrollView](https://reactnative.dev/docs/scrollview.html); eg: `scrollEnabled`、`onScroll` (if it not works, it is a mandatory prop of Carousel) ## Carousel ref methods Properties | Descrition | Type ----|-----|------ | goTo | jump to specified index | `(index: number, animated?: boolean): void` | | scrollNextPage | scroll to next page | `() => void` | ## FAQ ### 1. On the Android platform, when using `Carousel` nested in `ScrollView`, the Carousel Item cannot slide. What should I do? Support in `5.1.3`. Set the `nestedScrollEnabled` property of `ScrollView` to `true`. ```jsx ... ``` ### 2. Use `lazy` and `renderLazyPlaceholder` props to render routes as needed Support in `5.3.1`. ```jsx // `lazy={true}` only the current page is rendered } /> // eg: Render the sibling pages, a total of 3 pages Math.abs(selectedIndex - i) < 2} > ``` ### 3. Why choose Carousel instead of `react-native-pager-view` ? First, Carousel supports the `infinite` property, which means 🌟a true infinite loop🌟.
Second, Carousel is completely based on `ScrollView`, which is not only lighter but also more compatible. --- ## Checkbox Source: https://rn.mobile.ant.design/components/checkbox.md # Checkbox Checkbox ## Examples ```tsx import { Button, Checkbox, Flex, List, WingBlank } from '@ant-design/react-native' import React from 'react' import { ScrollView } from 'react-native' const AgreeItem = Checkbox.AgreeItem const CheckboxItem = Checkbox.CheckboxItem export default class BasicCheckboxExample extends React.Component { constructor(props: any, context: any) { super(props, context) this.state = { checked: true, disabled: false, checkBox1: true, agreeItem1: true, checkboxItem1: true, } } onChange = (e: { target: { checked: boolean } }) => { console.log(`checked = ${e.target.checked}`) } toggleChecked = () => { this.setState({ checked: !this.state.checked }) } toggleDisable = () => { this.setState({ disabled: !this.state.disabled }) } onChange2 = (e: { target: { checked: boolean } }) => { console.log('checked = ', e.target.checked) this.setState({ checked: e.target.checked, }) } render() { const label = `${this.state.checked ? 'Checked' : 'Unchecked'}-${ this.state.disabled ? 'Disabled' : 'Enabled' }` return ( Checkbox} /> } /> } /> }> {label} } /> Agree agreement agreement agreement agreement agreement agreement agreement { this.setState({ checkboxItem1: event.target.checked }) }}> Option 1 Option 2 Option 3 More... ) } } const plainOptions = ['Apple', 'Pear', 'Orange'] const defaultCheckedList = ['Apple', 'Orange'] const CheckboxGroupExample = () => { const [checkedList, setCheckedList] = React.useState( new Set(defaultCheckedList), ) const [indeterminate, setIndeterminate] = React.useState(true) const [checkAll, setCheckAll] = React.useState(false) const onChange = (value: any, e: { target: { checked: boolean } }) => { if (e.target.checked) { checkedList.add(value) } else { checkedList.delete(value) } setCheckedList(new Set(checkedList)) setIndeterminate( !!checkedList.size && checkedList.size < plainOptions.length, ) setCheckAll(checkedList.size === plainOptions.length) } const onCheckAllChange = (e: { target: { checked: boolean } }) => { setCheckedList(e.target.checked ? new Set(plainOptions) : new Set()) setIndeterminate(false) setCheckAll(e.target.checked) } return ( <> Check all {plainOptions.map((a) => ( {a} ))} ) } ``` ## API ### Checkbox ```ts type Event = { target: { checked: boolean } } ``` Properties | Descrition | Type | Default -----------|------------|------|-------- | defaultChecked | whether is checked when init | Boolean | | | checked | whether is checked now (Controlled Mode) | Boolean | | | disabled | whether is been disabled | Boolean | false | | indeterminate | The indeterminate checked state of checkbox | Boolean | false | | onChange | callback when check status is changed | (e: `Event`) => void | | ### Checkbox.CheckboxItem The encapsulation about `Checkbox` based on `List.Item`, the property `thumb` of `List.Item` will be passed to `Checkbox`, while other properties remain the same. Other APIs are identical with `Checkbox`. ### Checkbox.AgreeItem Almost the same as CheckboxItem and be used for special scenes. See demo for details. --- ## Collapse Source: https://rn.mobile.ant.design/components/collapse.md # Collapse A content area that can be collapsed/expanded. ### Rules - Group and hide complex areas to keep pages tidy. - An accordion is a special type of accordion panel that only allows a single content area to expand. ## Examples ```tsx import { ActivityIndicator, Collapse, Icon, List, Result } from '@ant-design/react-native' import React, { useEffect, useState } from 'react' import { ScrollView } from 'react-native' export default function CollapseExmple() { return ( 手风琴模式只能同时展开一个 手风琴模式只能同时展开一个 手风琴模式只能同时展开一个 active ? : }> 你可以通过 Collapse 的 arrow 属性来控制全部面板的箭头 }> 也可以通过 Collapse.Panel 的 arrow 属性来自定义单个面板的箭头 active ? ( ) : ( ) }> 如果你给 arrow 属性传入的是是一个渲染函数,那么 @ant-design/react-native 不会为你增加动画,arrow 属性的效果就完全交由你自己来控制了 ) } function DynamicContent(props: { message: string }) { const [finished, setFinished] = useState(false) useEffect(() => { const loadData = async () => { setTimeout(() => { setFinished(true) }, 1000) } loadData() }, []) return finished ? ( ) : ( ) } ``` ## API ### Collapse Properties | Descrition | Type | Default | -----------|------------|------|---------| | accordion | Whether to enable accordion mode | `Boolean` | `false` | | activeKey | The `key` of the currently expanded panel | accordion mode: `string | null`
non-accordion mode: `string[]` | - | | arrowIcon | Custom arrow icon.
if you pass a ReactNode, will add a rotate animation for you. | `ReactNode | ((active: boolean) => React.ReactNode)` | - | | defaultActiveKey | The `key` of the expanded panel by default | accordion mode: `string | null`
non-accordion mode: `string[]` | - | | onChange | Triggered when the panel is switched | accordion mode: `(activeKey: string | null) => void`
non-accordion mode: `(activeKey: string[]) => void` | - | | styles | Semantic DOM style | Same as [ListStyle](/components/list#liststyle-interface) & [ListItemStyle](/components/list#listitemstyle-interface) | - | ### Collapse.Panel Properties | Descrition | Type | Default | -----------|------------|------|---------| | arrowIcon | Custom arrow icon | `ReactNode | ((active: boolean) => React.ReactNode)` | - | | destroyOnClose | Destroy `dom` when not visible | `Boolean` | `false` | | disabled | Whether disabled or not | `Boolean` | `false` | | forceRender | Whether to render the `DOM` structure when hidden | `Boolean` | `false` | | key | The unique identifier | `String` | - | | onPress | The click event of title bar | `(event: GestureResponderEvent) => void` | - | | styles | Semantic DOM style | Same as [ListStyle](/components/list#liststyle-interface) | - | | title | The content on the left side of the title bar | `ReactNode` | - | --- ## DatePicker Source: https://rn.mobile.ant.design/components/date-picker.md # DatePicker Used to select a date or time. ### Rules - At most accurate to seconds. ## Examples ```tsx import { DatePicker, List, Provider } from '@ant-design/react-native' import React from 'react' export default class PopupExample extends React.Component { constructor(props: any) { super(props) this.state = { value: undefined, } } onChange = (value: any) => { this.setState({ value }) } render() { return ( Select Date ) } } ``` ## API ```ts type Precision = | 'week' | 'week-day' | 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' type DatePickerFilter = Partial< Record< Precision, ( val: number, extend: { date: Date } ) => boolean > > ``` Properties | Descrition | Type | Default | Version -----------|------------|------|--------|-------- | precision | Precision | `Precision` | `day` |`5.1.0`| | value | the currently selected value | Date | - || | defaultValue | the default selected value | Date | - || | minDate | minimum date | Date | 2000-1-1 || | maxDate | maximum date | Date | 2030-1-1 || | onChange | change handler | `(value: Date) => void` | - || | onValueChange | fire when picker col change | `(value: Date, index: number) => void` | - || | renderLabel | The function to custom rendering the label shown on a column. `type` means any value in `precision`, `data` means the default number | `(type:Precision / 'now', data: number) => ReactNode` | - || | locale | international, can override the configuration of the global [Provider](/components/provider)'s `locale` | Object: Object: {okText, dismissText, extra, `DatePickerLocale:{ year,month,day,hour,minute,am,pm }`} | - | | filter | Filter available time | `DatePickerFilter` | - | `5.1.0` | In addition, the following properties of [Picker](/components/picker) are supported: `onPickerChange` `onVisibleChange` `style` `styles` `itemStyle` `itemHeight` `numberOfLines` `title` `okText` `dismissText` `okButtonProps` `dismissButtonProps` `visible` `children` `renderMaskTop` `renderMaskBottom` ### Children Same as [Picker](/components/picker#children), except type `format` is different: Properties | Descrition | Type | Default ----|-----|------|------ | format | format the selected value |`(value: Date) => date string` | import [Day.js Format](https://day.js.org/docs/en/parse/string-format), precision:`YYYY-MM-DD`,`YYYY-MM-DD HH:mm:ss`| ### Ref Same as [Picker](/components/picker#ref) --- ## DatePickerView Source: https://rn.mobile.ant.design/components/date-picker-view.md # DatePickerView DatePickerView's functions like DatePicker, but it is rendered directly in the area instead of the pop-up window. ## Examples ```tsx import { DatePickerView, DatePickerFilter } from '@ant-design/react-native' import React, { useState } from 'react' import { ScrollView, Text } from 'react-native' const now = new Date() export default () => { const [value, setValue] = useState(now) return ( 基础用法 受控模式 { setValue(val) console.log('onChange', val) }} /> 自定义每列的渲染内容 周选择器 console.log('onChange', val)} precision="week-day" defaultValue={now} renderLabel={weekdayLabelRenderer} /> 过滤可供选择的时间 ) } const labelRenderer = (type: string, data: number) => { switch (type) { case 'year': return data + '年' case 'month': return data + '月' case 'day': return data + '日' case 'hour': return data + '时' case 'minute': return data + '分' case 'second': return data + '秒' default: return data } } const weekdayLabelRenderer = (type: string, data: number) => { switch (type) { case 'year': return data + '年' case 'week': return data + '周' case 'week-day': return weekdayToZh(data) default: return data } } const dateFilter: DatePickerFilter = { day: (_val, { date }) => { // 去除所有周末 if (date.getDay() > 5 || date.getDay() === 0) { return false } return true }, hour: (val: number) => { // 只保留每天的14点到18点 if (val < 14 || val > 18) { return false } return true }, } const weekdayToZh = (weekday: number) => { switch (weekday) { case 1: return '周一' case 2: return '周二' case 3: return '周三' case 4: return '周四' case 5: return '周五' case 6: return '周六' case 7: return '周日' default: return weekday } } ``` ## API ```ts type Precision = | 'week' | 'week-day' | 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' type DatePickerFilter = Partial< Record< Precision, ( val: number, extend: { date: Date } ) => boolean > > ``` Properties | Descrition | Type | Default | Version -----------|------------|------|---------|--------- | precision | Precision | `Precision` | `day` |`5.1.0`| | value | the currently selected value | Date | - | | defaultValue | the default selected value | Date | - || | minDate | minimum date | Date | 2000-1-1 | | maxDate | maximum date | Date | 2030-1-1 | | onChange | change handler | `(value: Date) => void` | - || | onValueChange | fire when picker col change | `(value: Date, index: number) => void` | - || | renderLabel | The function to custom rendering the label shown on a column. `type` means any value in `precision`, `data` means the default number | `(type:Precision / 'now', data: number) => ReactNode` | - || | filter | Filter available time | `DatePickerFilter` | - | `5.1.0` | In addition, the following properties of [PickerView](/components/picker-view) are supported: `style` `styles` `itemStyle` `itemHeight` `numberOfLines` `renderMaskTop` `renderMaskBottom` --- ## DatePickerView Source: https://rn.mobile.ant.design/components/image-picker.md # DatePickerView Deprecated since `5.1.0`. --- ## Drawer Source: https://rn.mobile.ant.design/components/drawer.md # Drawer Drawer is a panel that displays the app's navigation options on the left edge of the screen. ### Rules - Recommended way to show navigation options on Android, it is a common pattern found in Android APPs. ## Examples ```tsx import { Button, Drawer, List, WhiteSpace } from '@ant-design/react-native' import React from 'react' import { ScrollView, StyleSheet, Text, View } from 'react-native' const styles = StyleSheet.create({ container: { flex: 1, }, }) export default class DrawerExample extends React.Component { drawer: any onOpenChange = (isOpen: any) => { /* tslint:disable: no-console */ console.log('是否打开了 Drawer', isOpen.toString()) } render() { const itemArr = Array.apply(null, Array(20)) .map(function (_: any, i: any) { return i }) .map((_i: any, index: any) => { if (index === 0) { return ( Categories - {index} ) } return ( Categories - {index} ) }) // Todo: https://github.com/DefinitelyTyped/DefinitelyTyped const sidebar = ( {itemArr} ) return ( (this.drawer = el)} onOpenChange={this.onOpenChange} drawerBackgroundColor="#ccc"> ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | sidebar | The sidebar content. | ReactNode | - | | onOpenChange | Callback called when open state of `Drawer` changes. | (open: bool): void | - | | open | If the sidebar should be open. | Boolean | false | | position | Position of `Drawer`. | String | 'left', enum{'left', 'right'} | | drawerWidth | Width of `Drawer` | Number | 300 | | drawerBackgroundColor | Background color of `Drawer` | String | - | | openDrawer | Opens the `Drawer`. | (): void | - | | closeDrawer | Closes the `Drawer`. | (): void | - | --- ## Flex Source: https://rn.mobile.ant.design/components/flex.md # Flex Flex is a wrap of Flexible Box. ## Examples ```tsx import { Button, Flex, WhiteSpace, WingBlank } from '@ant-design/react-native' import React from 'react' import { ScrollView, Text, TouchableWithoutFeedback, View } from 'react-native' const Circle = (props: any) => { const size = props.size || 20 const style = { borderRadius: size / 2, backgroundColor: '#527fe4', width: size, height: size, margin: 1, } return } export default class FlexExample extends React.Component { render() { return ( 项目的排列方向 direction="row":主轴为水平方向,起点在左端 direction="column":主轴为垂直方向,起点在上沿 项目在主轴上的对齐方式 justify="start":左对齐 justify="center":居中 justify="end":右对齐 justify="between":两端对齐,项目之间的间隔都相等 justify="around":每个项目两侧的间隔相等 项目在交叉轴上的对齐方式 align="start":交叉轴的起点对齐 兜兜 兜兜 兜兜 兜兜 align="center":交叉轴的中点对齐 兜兜 兜兜 兜兜 兜兜 align="end":交叉轴的终点对齐 兜兜 兜兜 兜兜 兜兜 align="stretch":如果项目未设置高度或设为auto,将占满整个容器的高度 兜兜 兜兜 兜兜 兜兜 是否折行 wrap="wrap":换行 ({})}> {'ooooooooooooooooooooooooooooo'.split('').map((char, i) => ( ))} wrap="nowrap":不换行 ({})}> {'ooooooooooooooooooooooooooooo'.split('').map((char, i) => ( ))} ) } } ``` ## API ### Flex Properties | Descrition | Type | Default -----------|------------|------|-------- | direction | how flex items are placed in the flex container,value could be `row`,`row-reverse`,`column`,`column-reverse`, RN only support `row`,`column` | String | `row` | | wrap | the wrap way of sub-elements,option `nowrap`,`wrap`,`wrap-reverse`,RN only support `nowrap`,`wrap` | String | `nowrap` | | justify | the way of alignment for sub-elements of main axis, option `start`,`end`,`center`,`between`,`around` | String | `start` | | align | the way of alignment for sub-elements of cross-axis, option `start`,`center`,`end`,`baseline`,`stretch` RN only support `start`,`end`,`center`,`stretch` | String | `center` | ### Flex.Item Flex.Item component has style `flex:1` as default, ensure all items average division width, Flex container‘s children maybe not Flex.Item. --- ## Form Source: https://rn.mobile.ant.design/components/form.md # Form High-performance form component with data domain management. Includes data entry, validation, and corresponding styles. Base on [rc-field-form](https://www.npmjs.com/package/rc-field-form). Example from https://ant.design/components/form-cn ## When to use - When you need to create an instance or collect information. - When you need to validate fields in certain rules. ## Examples ```tsx import { Button, Form, Input, Picker, Provider, Radio, Flex as Row, Switch, } from '@ant-design/react-native' import type { FormProps } from '@ant-design/react-native/lib/form' import { district } from 'antd-mobile-demo-data' import React from 'react' import { KeyboardAvoidingView, Platform, ScrollView } from 'react-native' const Col = Row.Item type FieldType = { username?: string password?: string remember?: string isDefault?: boolean } const FormExample: React.FC = () => { const [form] = Form.useForm() const onSubmit = () => { form.submit() } const onFinish: FormProps['onFinish'] = (values) => { console.log('Success:', values) } const onFinishFailed: FormProps['onFinishFailed'] = ( errorInfo, ) => { console.log('Failed:', errorInfo) } const pickerRef = React.useRef(null) return (
{ pickerRef.current.toggle() }}> {({ extra, value, toggle }) => ( )} 先生 女士 }>
) } export default FormExample ``` ## API ### Form | Property | Description | Type | Default | | --- | --- | --- | --- | | disabled | Set form component disable, only available for `@ant-design/react-native` components | boolean | false | | component | Set the Form rendering element. Do not create a ReactNode for `false` | ComponentType \| false | `List` | | fields | Control of form fields through state management (such as redux). Not recommended for non-strong demand. View [example](https://ant.design/components/form#components-form-demo-global-state) | [FieldData](#fielddata)\[] | - | | form | Form control instance created by `Form.useForm()`. Automatically created when not provided | [FormInstance](#forminstance) | - | | feedbackIcons | Can be passed custom icons while `Form.Item` element has `hasFeedback` | [FeedbackIcons](#feedbackicons) | - | | initialValues | Set value by Form initialization or reset | object | - | | labelStyle | The label style | `ViewStyle \| TextStyle` | - | | layout | Form layout | `horizontal` \| `vertical` | `horizontal` | | name | Form name. Will be the prefix of Field `id` | string | - | | preserve | Keep field value even when field removed. You can get the preserve field value by `getFieldsValue(true)` | boolean | true | | requiredMark | Required mark style. Can use required mark or optional mark. You can not config to single Form.Item since this is a Form level config | boolean \| `optional` \| ((label: ReactNode, info: { required: boolean }) => ReactNode) | true | | validateMessages | Validation prompt template, description [see below](#validatemessages) | [ValidateMessages](https://github.com/ant-design/ant-design/blob/6234509d18bac1ac60fbb3f92a5b2c6a6361295a/components/locale/en_US.ts#L88-L134) | - | | validateTrigger | Config field validate trigger | string \| string\[] | `onChange` | | wrapperStyle | The layout for input controls, same as `labelStyle` | `ViewStyle` | - | | onFieldsChange | Trigger when field updated | function(changedFields, allFields) | - | | onFinish | Trigger after submitting the form and verifying data successfully | function(values) | - | | onFinishFailed | Trigger after submitting the form and verifying data failed | function({ values, errorFields, outOfDate }) | - | | onValuesChange | Trigger when value updated | function(changedValues, allValues) | - | | styles | Semantic DOM style | Same as [ListStyle](/components/list#liststyle-interface) | - | ### validateMessages Form provides [default verification error messages](https://github.com/ant-design/ant-design/blob/6234509d18bac1ac60fbb3f92a5b2c6a6361295a/components/locale/en_US.ts#L88-L134). You can modify the template by configuring `validateMessages` property. A common usage is to configure localization: ```jsx const validateMessages = { required: "'${name}' is required!", // ... };
; ``` ## Form.Item Form field component for data bidirectional binding, validation, layout, and so on. | Property | Description | Type | Default | | --- | --- | --- | --- | | dependencies | Set the dependency field. See [below](#dependencies) | [NamePath](#namepath)\[] | - | | getValueFromEvent | Specify how to get value from event or other onChange arguments | (..args: any\[]) => any | - | | getValueProps | Additional props with sub component (It's not recommended to generate dynamic function prop by `getValueProps`. Please pass it to child component directly) | (value: any) => Record | - | | hasFeedback | Used with `validateStatus`, this option specifies the validation status icon. Recommended to be used only with `Input`. Also, It can get feedback icons via icons prop. | boolean \| { icons: [FeedbackIcons](#feedbackicons) } | false | | help | The prompt message. If not provided, the prompt message will be generated by the validation rule. | ReactNode | - | | hidden | Whether to hide Form.Item (still collect and validate value) | boolean | false | | initialValue | Config sub default value. Form `initialValues` get higher priority when conflict | string | - | | label | Label text | ReactNode | - | | labelStyle | The label style. You can set `labelCol` on Form which will not affect nest Item. If both exists, use Item first | `ViewStyle \| TextStyle` | - | | messageVariables | The default validate field info | Record<string, string> | - | | name | Field name, support array | [NamePath](#namepath) | - | | normalize | Normalize value from component value before passing to Form instance. Do not support async | (value, prevValue, prevValues) => any | - | | noStyle | No style for `true`, used as a pure field control. Will inherit parent Form.Item `validateStatus` if self `validateStatus` not configured | boolean | false | | preserve | Keep field value even when field removed | boolean | true | | required | Display required style. It will be generated by the validation rule | boolean | false | | rules | Rules for field validation. Click [here](https://ant.design/components/form#components-form-demo-basic) to see an example | [Rule](#rule)\[] | - | | shouldUpdate | Custom field update logic. See [below](#shouldupdate) | boolean \| (prevValue, curValue) => boolean | false | | styles | Semantic DOM style | [FormItemStyle](#formitemstyle-interface) & [ValidateStatusStyle](#validatestatusstyle-interface) | - | | trigger | When to collect the value of children node. Click [here](https://ant.design/components/form#components-form-demo-customized-form-controls) to see an example | string | `onChange` | | validateDebounce | Delay milliseconds to start validation | number | - | | validateFirst | Whether stop validate on first rule of error for this field. Will parallel validate when `parallel` configured | boolean \| `parallel` | false | | validateStatus | The validation status. If not provided, it will be generated by validation rule. options: `success` `warning` `error` `validating` | string | - | | validateTrigger | When to validate the value of children node | string \| string\[] | `onChange` | | valuePropName | Props of children node, for example, the prop of Switch or Checkbox is `checked`. This prop is an encapsulation of `getValueProps`, which will be invalid after customizing `getValueProps` | string | `value` | | wrapperStyle | The layout for input controls, same as `labelStyle`. You can set `wrapperStyle` on Form which will not affect nest Item. If both exists, use Item first | `ViewStyle` | - | The layout of Form.Item is based on List.Item. So it also supports these props of [List.Item](/components/list/#List.Item) `arrow` `extra` `thumb` After wrapped by `Form.Item` with `name` property, `value`(or other property defined by `valuePropName`) `onChange`(or other property defined by `trigger`) props will be added to form controls, the flow of form data will be handled by Form which will cause: 1. You shouldn't use `onChange` on each form control to **collect data**(use `onValuesChange` of Form), but you can still listen to `onChange`. 2. You cannot set value for each form control via `value` or `defaultValue` prop, you should set default value with `initialValues` of Form. Note that `initialValues` cannot be updated by `setState` dynamically, you should use `setFieldsValue` in that situation. 3. You shouldn't call `setState` manually, please use `form.setFieldsValue` to change value programmatically. ### dependencies Used when there are dependencies between fields. If a field has the `dependencies` prop, this field will automatically trigger updates and validations when upstream is updated. A common scenario is a user registration form with "password" and "confirm password" fields. The "Confirm Password" validation depends on the "Password" field. After setting `dependencies`, the "Password" field update will re-trigger the validation of "Check Password". `dependencies` shouldn't be used together with `shouldUpdate`, since it may result in conflicting update logic. ### FeedbackIcons `({ status: ValidateStatus, errors: ReactNode, warnings: ReactNode }) => Record` ### shouldUpdate Form updates only the modified field-related components for performance optimization purposes by incremental update. In most cases, you only need to write code or do validation with the [`dependencies`](#dependencies) property. In some specific cases, such as when a new field option appears with a field value changed, or you just want to keep some area updating by form update, you can modify the update logic of Form.Item via the `shouldUpdate`. When `shouldUpdate` is `true`, any Form update will cause the Form.Item to be re-rendered. This is very helpful for custom rendering some areas. It should be noted that the child component should be returned in a function, otherwise `shouldUpdate` won't behave correctly: ```jsx {() => { return
{JSON.stringify(form.getFieldsValue(), null, 2)}
; }}
``` When `shouldUpdate` is a function, it will be called by form values update. Providing original values and current value to compare. This is very helpful for rendering additional fields based on values: ```jsx prevValues.additional !== curValues.additional}> {() => { return ( ); }} ``` ### messageVariables You can modify the default verification information of Form.Item through `messageVariables`. ```jsx user} rules={[{ required: true, message: '${label} is required' }]} > ``` ## Form.List Provides array management for fields. | Property | Description | Type | Default | | --- | --- | --- | --- | | children | Render function | (fields: Field\[], operation: { add, remove, move }, meta: { errors }) => React.ReactNode | - | | initialValue | Config sub default value. Form `initialValues` get higher priority when conflict | any\[] | - | | name | Field name, support array. List is also a field, so it will return all the values by `getFieldsValue`. You can change this logic by [config](#getfieldsvalue) | [NamePath](#namepath) | - | | rules | Validate rules, only support customize validator. Should work with [ErrorList](#formerrorlist) | { validator, message }\[] | - | ```tsx {(fields) => (
{fields.map((field) => ( ))}
)}
``` Note: You should not configure Form.Item `initialValue` under Form.List. It always should be configured by Form.List `initialValue` or Form `initialValues`. ## operation Some operator functions in render form of Form.List. | Property | Description | Type | Default | | --- | --- | --- | --- | | add | add form item | (defaultValue?: any, insertIndex?: number) => void | insertIndex | | move | move form item | (from: number, to: number) => void | - | | remove | remove form item | (index: number \| number\[]) => void | number\[] | ## Form.ErrorList Show error messages, should only work with `rules` of Form.List. See [example](https://ant.design/components/form#components-form-demo-dynamic-form-item). | Property | Description | Type | Default | | -------- | ----------- | ------------ | ------- | | errors | Error list | ReactNode\[] | - | | styles | Semantic DOM style | [ValidateStatusStyle](#validatestatusstyle-interface) | - | ## Form.Provider Provide linkage between forms. If a sub form with `name` prop update, it will auto trigger Provider related events. See [example](https://ant.design/components/form#components-form-demo-form-context). | Property | Description | Type | Default | | --- | --- | --- | --- | | onFormChange | Triggered when a sub form field updates | function(formName: string, info: { changedFields, forms }) | - | | onFormFinish | Triggered when a sub form submits | function(formName: string, info: { values, forms }) | - | ```jsx { if (name === 'form1') { // Do something... } }} >
...
...
``` ### FormInstance | Name | Description | Type | | --- | --- | --- | | getFieldError | Get the error messages by the field name | (name: [NamePath](#namepath)) => string\[] | | getFieldInstance | Get field instance | (name: [NamePath](#namepath)) => any | | getFieldsError | Get the error messages by the fields name. Return as an array | (nameList?: [NamePath](#namepath)\[]) => FieldError\[] | | getFieldsValue | Get values by a set of field names. Return according to the corresponding structure. Default return mounted field value, but you can use `getFieldsValue(true)` to get all values | [GetFieldsValue](#getfieldsvalue) | | getFieldValue | Get the value by the field name | (name: [NamePath](#namepath)) => any | | isFieldsTouched | Check if fields have been operated. Check if all fields is touched when `allTouched` is `true` | (nameList?: [NamePath](#namepath)\[], allTouched?: boolean) => boolean | | isFieldTouched | Check if a field has been operated | (name: [NamePath](#namepath)) => boolean | | isFieldValidating | Check field if is in validating | (name: [NamePath](#namepath)) => boolean | | resetFields | Reset fields to `initialValues` | (fields?: [NamePath](#namepath)\[]) => void | | scrollToField | Scroll to field position | (name: [NamePath](#namepath), options: \[[ScrollOptions](https://github.com/stipsan/scroll-into-view-if-needed/tree/ece40bd9143f48caf4b99503425ecb16b0ad8249#options)]) => void | | setFields | Set fields status | (fields: [FieldData](#fielddata)\[]) => void | | setFieldValue | Set fields value(Will directly pass to form store and **reset validation message**. If you do not want to modify passed object, please clone first) | (name: [NamePath](#namepath), value: any) => void | | setFieldsValue | Set fields value(Will directly pass to form store and **reset validation message**. If you do not want to modify passed object, please clone first). Use `setFieldValue` instead if you want to only config single value in Form.List | (values) => void | | submit | Submit the form. It's same as click `submit` button | () => void | | validateFields | Validate fields. Use `recursive` to validate all the field in the path | (nameList?: [NamePath](#namepath)\[], config?: [ValidateConfig](#validateFields)) => Promise | #### validateFields ```tsx export interface ValidateConfig { // Only validate content and not show error message on UI. validateOnly?: boolean; // Recursively validate the provided `nameList` and its sub-paths. recursive?: boolean; // Validate dirty fields (touched + validated). // It's useful to validate fields only when they are touched or validated. dirty?: boolean; } ``` return sample: ```jsx validateFields() .then((values) => { /* values: { username: 'username', password: 'password', } */ }) .catch((errorInfo) => { /* errorInfo: { values: { username: 'username', password: 'password', }, errorFields: [ { name: ['password'], errors: ['Please input your Password!'] }, ], outOfDate: false, } */ }); ``` ### FormItemStyle interface ```typescript interface FormItemStyle extends ListItemStyle { // label prop formItemLabel: ViewStyle // { minWidth: 65 } formItemLabelText: ViewStyle | TextStyle // children style formItemControl: ViewStyle // required={true} asterisk: TextStyle // requiredMark="optional" optional: TextStyle } ``` ### ValidateStatusStyle interface when set `validateStatus` prop ```typescript interface ValidateStatusStyle { error: TextStyle warning: TextStyle success: TextStyle validating: TextStyle feedbackIcon: ViewStyle } ``` ## Hooks ### Form.useForm `type Form.useForm = (): [FormInstance]` Create Form instance to maintain data store. ### Form.useFormInstance `type Form.useFormInstance = (): FormInstance` Get current context form instance to avoid pass as props between components: ```tsx const Sub = () => { const form = Form.useFormInstance(); return
); }; ``` ### Form.Item.useStatus `type Form.Item.useStatus = (): { status: ValidateStatus | undefined, errors: ReactNode[], warnings: ReactNode[] }` Could be used to get validate status of Form.Item. If this hook is not used under Form.Item, `status` would be `undefined`. `error` and `warnings` could be used to get error messages and warning messages of Form.Item: ```tsx const CustomInput = ({ value, onChange }) => { const { status, errors } = Form.Item.useStatus(); return ( ); }; export default () => (
); ``` #### Difference between other data fetching method Form only update the Field which changed to avoid full refresh perf issue. Thus you can not get real time value with `getFieldsValue` in render. And `useWatch` will rerender current component to sync with latest value. You can also use Field renderProps to get better performance if only want to do conditional render. If component no need care field value change, you can use `onValuesChange` to give to parent component to avoid current one rerender. ### Interface #### NamePath `string | number | (string | number)[]` #### GetFieldsValue `getFieldsValue` provides overloaded methods: ##### getFieldsValue(nameList?: true | [NamePath](#namepath)\[], filterFunc?: FilterFunc) When `nameList` is empty, return all registered fields, including values of List (even if List has no Item children). When `nameList` is `true`, return all values in store, including unregistered fields. For example, if you set the value of an unregistered Item through `setFieldsValue`, you can also get all values through `true`. When `nameList` is an array, return the value of the specified path. Note that `nameList` is a nested array. For example, you need the value of a certain path as follows: ```tsx // Single path form.getFieldsValue([['user', 'age']]); // multiple path form.getFieldsValue([ ['user', 'age'], ['preset', 'account'], ]); ``` ##### getFieldsValue({ strict?: boolean, filter?: FilterFunc }) Accept configuration parameters. When `strict` is `true`, only the value of Item will be matched. For example, in `{ list: [{ bamboo: 1, little: 2 }] }`, if List is only bound to the `bamboo` field, then `getFieldsValue({ strict: true })` will only get `{ list: [{ bamboo: 1 }] }`. #### FilterFunc To filter certain field values, `meta` will provide information related to the fields. For example, it can be used to retrieve values that have only been modified by the user, and so on. ```tsx type FilterFunc = (meta: { touched: boolean; validating: boolean }) => boolean; ``` #### FieldData | Name | Description | Type | | ---------- | ------------------------ | ------------------------ | | errors | Error messages | string\[] | | warnings | Warning messages | string\[] | | name | Field name path | [NamePath](#namepath)\[] | | touched | Whether is operated | boolean | | validating | Whether is in validating | boolean | | value | Field value | any | #### Rule Rule supports a config object, or a function returning config object: ```tsx type Rule = RuleConfig | ((form: FormInstance) => RuleConfig); ``` | Name | Description | Type | | --- | --- | --- | | defaultField | Validate rule for all array elements, valid when `type` is `array` | [rule](#rule) | | enum | Match enum value. You need to set `type` to `enum` to enable this | any\[] | | fields | Validate rule for child elements, valid when `type` is `array` or `object` | Record<string, [rule](#rule)> | | len | Length of string, number, array | number | | max | `type` required: max length of `string`, `number`, `array` | number | | message | Error message. Will auto generate by [template](#validatemessages) if not provided | string | | min | `type` required: min length of `string`, `number`, `array` | number | | pattern | Regex pattern | RegExp | | required | Required field | boolean | | transform | Transform value to the rule before validation | (value) => any | | type | Normally `string` \|`number` \|`boolean` \|`url` \| `email`. More type to ref [here](https://github.com/yiminghe/async-validator#type) | string | | validateTrigger | Set validate trigger event. Must be the sub set of `validateTrigger` in Form.Item | string \| string\[] | | validator | Customize validation rule. Accept Promise as return. See [example](https://ant.design/components/form#components-form-demo-register) | ([rule](#rule), value) => Promise | | warningOnly | Warning only. Not block form submit | boolean | | whitespace | Failed if only has whitespace, only work with `type: 'string'` rule | boolean | #### WatchOptions | Name | Description | Type | Default | | --- | --- | --- | --- | | form | Form instance | FormInstance | Current form in context | | preserve | Whether to watch the field which has no matched `Form.Item` | boolean | false | ## FAQ ### Why can't Switch、Checkbox、Radio bind data? Form.Item default bind value to `value` prop, but Switch or Checkbox value prop is `checked`. You can use `valuePropName` to change bind value prop. ```tsx | pure ``` ### How does Form.Item work with Picker / DatePicker? When Picker's `children` is `List.Item`, it can be used directly.
Note: Form.Item need `noStyle` prop ```tsx 地址 ``` However, we recommend the composition layout of `Form.Item` and `Input`, so how to use it when `children` is not `List.Item`?
When `children` is a **function**, the `toggle` parameter will be provided to control the display/hide of Picker. ```tsx {({ extra, value, toggle }: any) => ( )} ``` Secondly, you can use `ref` ```tsx const pickerRef = useRef(); pickerRef.current?.toggle()}> ``` ### Is there any more reference documentation? https://ant.design/components/form-cn --- ## Grid Source: https://rn.mobile.ant.design/components/grid.md # Grid We divided the design area into a number of aliquots in horizontal and vertical. ### Rules - The contents of the blocks should have the same type. eg: they are all pictures or icons with text. ## Examples ```tsx import { Grid } from '@ant-design/react-native' import React from 'react' import { ScrollView, Text, View } from 'react-native' const data = Array.from(new Array(9)).map((_val, i) => ({ icon: 'https://os.alipayobjects.com/rmsportal/IptWdCkrtkAUfjE.png', text: `Name${i}`, })) export default class BasicGridExample extends React.Component { render() { return ( Simple Carousel alert(index)} /> Custom GridCell Style ) } } ``` ## API | Properties | Description | Type | Default | | -------------- | ------------------------------------------------------------- | --------------------------------- | ----------- | | data | data record array to be rendered | `Array<{icon, text}>` | [] | | onPress | Handler to be called when the user taps the grid | (el: Object, index: number): void | - | | columnNum | the number of columns | number | `4` | | hasLine | whether to show border | boolean | `true` | | isCarousel | whether to be played as a Carousel | boolean | `false` | | carouselProps | Carousel Props | CarouselProps | `{}` | | carouselMaxRow | the max number of rows to be showed each page of the Carousel | number | `2` | | renderItem | custom function to create each grid item | (el, index) => React.Node | - | | itemStyle | Custom GridCell Style | object | {} | When `isCarousel = true`, the APIs of [carousel](https://mobile.ant.design/components/carousel) also can be delivered. --- ## Icon Source: https://rn.mobile.ant.design/components/icon.md # Icon ## How to Use ### 安装依赖 ```bash npm install @ant-design/icons-react-native@latest ``` ### Linking - Add assets to your `react-native.config.js` ( If not exist, please create in project’s root directory ) ```js module.exports = { assets: ['node_modules/@ant-design/icons-react-native/fonts'], }; ``` - Run the [`react-native-asset`](https://github.com/unimonkiez/react-native-asset)'s command and linking + unlinking is automatic ```bash npx react-native-asset ``` will copy fonts to `ios` and `android` assets folder. - If you have an Expo managed project, skip the previous two steps and use [expo-font](https://docs.expo.dev/versions/latest/sdk/font/) to load the font directly: ```jsx import { useFonts } from 'expo-font'; const [fontsLoaded] = useFonts({ antoutline: require('@ant-design/icons-react-native/fonts/antoutline.ttf'), }) ``` ## Examples ```tsx import { outlineGlyphMap, OutlineGlyphMapType, } from '@ant-design/icons-react-native/lib/outline' import { Grid, Icon, SearchBar, Toast } from '@ant-design/react-native' import React from 'react' import { ScrollView } from 'react-native' const data = Object.keys(outlineGlyphMap).map((item: OutlineGlyphMapType) => ({ icon: , text: item, })) export default class IConDemo extends React.Component { state = { data, } handlePress = (dataItem: { icon?: any; text?: string }) => { Toast.show(``) } render() { return ( { this.setState(() => ({ data: data.filter((d) => d.text.match(new RegExp(text, 'gi'))), })) }} /> ) } } export const title = 'Icon' export const description = 'Icon Example' ``` ## API | Properties | Description | Type | Default | | ---------- | ------------------- | ---------------------------------- | ------- | | name | `OutlineGlyphMapType` | string | | size | icon size | 'xxs'/'xs'/'sm'/'md'/'lg' / number | `md` | | color | icon color | Color | '#000' | - Tips1: Clicking the icon in the demo will automatically copy the code to the ``. - Tips2: By default, Icon uses the `outline` icon in `ant-design-icons` --- ## Input Source: https://rn.mobile.ant.design/components/input.md # Input Entering content through the keyboard is the most basic form field wrapper. ### Rule - It is generally used in form pages to collect information, and provides two types of text boxes and text-area boxes. - The Input component is layout-independent. It can be used with the `List` component for quick layout; it also has built-in linkage interaction with the `Form` component. ## Examples ```tsx import { Input, List } from '@ant-design/react-native' import React from 'react' import { KeyboardAvoidingView, Platform, ScrollView } from 'react-native' export default function InputExample() { const [value, setValue] = React.useState('') return ( `${count}/${maxLength}`, }} placeholder="showCount.formatter" /> ) } ``` ## API ### Input | Properties | Description | Type | Default | | --- | --- | --- | --- | | allowClear | If allow to remove input content with clear icon | `boolean` \| `{ clearIcon: ReactNode }` | - | | defaultValue | The initial input content | string | - | | disabled | Whether the input is disabled | boolean | false | | maxLength | The maximum number of characters in Input | number | - | | prefix | The prefix icon for the Input | ReactNode | - | | showCount | Whether to show character count | `boolean` \| `{ formatter: (info: { value: string, count: number, maxLength?: number }) => ReactNode }` | false | | status | Set validation status | 'error' \| 'warning' | - | | inputStyle | TextInput style | `StyleProp` | - | | style | Container style | `StyleProp` | - | | styles | Semantic DOM style | [InputStyle](#inputstyle-interface) | - | | suffix | The suffix icon for the Input | ReactNode | - | | type | Declare the Input type, the same as the native [keyboardType](http://facebook.github.io/react-native/docs/textinput.html#keyboardtype) attribute | 'text' \| 'number' \| 'password' \| KeyboardTypeOptions | `text` | | value | The input content value | string | - | | onChange | Callback when user input, extra return `e.target.value` | `(e: NativeSyntheticEvent) => void;` | - | The rest of the props of Input are exactly the same as the react-native [TextInput](http://facebook.github.io/react-native/docs/textinput.html). ### Input.TextArea Same as Input, and more: | Property | Description | Type | Default | | --- | --- | --- | --- | | autoSize | Height auto size feature, can be set to `true` \| `false` or an object `{ minRows: 2, maxRows: 6 }` | boolean \| object | false | | rows | sets the number of lines for a textarea. Prioritize`autoSize` | number | 2 | | styles | Semantic DOM style | [InputStyle](#inputstyle-interface) | - | ### InputStyle interface ```typescript interface InputStyle { container: ViewStyle // Same as `style` prop input: ViewStyle // Same as `inputStyle` prop clearIcon: ViewStyle prefix: ViewStyle | TextStyle showCount: TextStyle suffix: ViewStyle | TextStyle warning: TextStyle error: TextStyle } ``` ## Ref Ref to [TextInput](http://facebook.github.io/react-native/docs/textinput.html) ## FAQ ## When setting `allowClear` on the Android platform, why does it not work when I click clearIcon? In Android, clearIcon will only appear when you are in editing state (`focus`).
When this component is wrapped by `ScrollView`, set the `keyboardShouldPersistTaps` property to `handled` or `always`, the icon will respond correctly to the click event ```jsx ... ``` ### Why Input in control can make `value` exceed `maxLength`? When in control, component should show as what it set to avoid submit value not align with store value in Form. --- ## InputItem Source: https://rn.mobile.ant.design/components/input-item.md # InputItem > This package has been deprecated in `5.2.1`, recommend [components/Input](/components/input) A foundational component for inputting text into the app via a keyboard. ### Rule - Support text input via keyboard or clipboard. - The cursor can be moved horizontally. - Handle text with a specific format, eg: hide password. ## Examples ```tsx import { Button, InputItem, List } from '@ant-design/react-native' import React from 'react' import { ScrollView, Text } from 'react-native' declare var jest: any export default class BasicInputItemExample extends React.Component { inputRef: any constructor(props: any) { super(props) this.state = { value: '', value1: '', value2: '', value3: '', value4: '', labelnum1: '', labelnum2: '', labelnum3: '', text: '', bankCard: '', phone: '', password: '', number: '', } } render() { return ( { this.setState({ value, }) }} extra="元" placeholder="有标签"> 输入框 { this.setState({ value, }) }} extra={} placeholder="不可编辑" editable={false}> 输入框 { this.setState({ value, }) }} extra={} placeholder="disabled" disabled> 输入框 { this.setState({ value1: value, }) }} placeholder="无标签" /> 标题 (this.inputRef = el)}> 标题 { this.setState({ labelnum1: value, }) }} labelNumber={2} placeholder="两个字标签"> 姓名 { this.setState({ labelnum2: value, }) }} labelNumber={3} placeholder="三个字标签"> 校验码 { this.setState({ labelnum3: value, }) }} labelNumber={4} placeholder="四个字标签(默认)"> 四字标签 { this.setState({ text: value, }) }} placeholder="text"> 文本输入 { this.setState({ bankcard: value, }) }} placeholder="bankCard"> 银行卡 { this.setState({ phone: value, }) }} placeholder="phone"> 手机号 { this.setState({ password: value, }) }} placeholder="password"> 密码 { this.setState({ number: value, }) }} placeholder="number"> 数字 ) } } ``` ## API **`InputItem` must wrapped by a [List](https://mobile.ant.design/components/list)** Properties | Description | Type | Default -----------|------------|------|-------- | type | can be `bankCard`; `phone`(which the maxLength is 11 and setting will be ignored); `password`; `number`(in order to evoke the 'numeric keyboard with decimal', this type is not a native number, but ``); `digit`(represent the native type number); As well as other standard html input type values. | String | `text` | | value | the value of input (see [react doc](https://facebook.github.io/react/docs/forms.html) for more information about controled component) | String | | | defaultValue | provides an initial value that will change when the user starts typing. | String | - | | placeholder | the string that will be rendered before text input has been entered. | String | '' | | editable | whether is editable | bool | true | | disabled | whether is disabled | bool | true | | clear | whether to display clear(it takes effect only `editable` is `true` and `disabled` is `false` has been set) | bool | false | | maxLength | limits the maximum number of characters that can be entered | number | | | onChange | callback that is called when the text input's text changes | (val: string): void | - | | onBlur | callback that is called when the text input is blurred | (val: string): void | - | | onFocus | callback that is called when the text input is focused | (val: string): void | - | | error | whether to display error | bool | false | | onErrorClick | callback that is called when the error icon is clicked | (e: Object): void | | | extra | the right content of `InputItem` | string or node | '' | | onExtraClick | callback that is called when the extra content is clicked | (e: Object): void | | | onVirtualKeyboardConfirm | callback that is called when "confirm" button of virtual keyboard is clicked | (val: string): void | | | labelNumber | number of label text, valid value is 2 to 7 | number | `5` | | locale | 国际化,可覆盖全局`[LocaleProvider](https://mobile.ant.design/components/locale-provider)`的配置, when`type`is`money`,can cunstom the keyboard confirm item's label | Object: { confirmLabel } | 无 | | last | If it is the last item, the `borderBottom` will be removed, the default has `borderBottom` | bool | false | > More available react-native `InputItem` API can be found at [react-native TextInput](http://facebook.github.io/react-native/docs/textinput.html) > Note: `InputItem` does not support negative number if `type` is text, you can use `type=text` to do that. ## InputItem Instance methods Property | Description | Type | Default ----|-----|------|------ | focus | Force focus back onto the input node | (): void | - | --- ## List Source: https://rn.mobile.ant.design/components/list.md # List A single and continuous block content is vertically arranged to display current contents, status and available operations. eg:Contact List. In case you need an infinite scroll list - consider using [ListView](https://mobile.ant.design/components/list-view/) component. ### Rule - Generally `List` consists of main infomation, main operations, secondary infomation and secondary operations. - The main infomation and main operations are placed on the left side of list, and secondary infomation and secondary operations are placed on the right side. ## Examples ```tsx import { List } from '@ant-design/react-native' import React from 'react' import { Image, ScrollView, View } from 'react-native' const Item = List.Item const Brief = Item.Brief export default class BasicListExample extends React.Component { render() { return ( 标题文字点击无反馈,文字超长则隐藏,文字超长则隐藏 文字超长折行文字超长折行文字超长折行文字超长折行文字超长折行 {}}> 标题文字 {}}> 标题文字 {}}> 标题文字 标题文字 内容内容 辅助文字内容
} multipleLine> 垂直居中对齐 垂直居中对齐辅助文字内容 顶部对齐 辅助文字内容辅助文字内容辅助文字内容辅助文字内容 辅助文字内容 内容内容 辅助文字内容 } multipleLine align="bottom"> 底部对齐 thumb thumb } arrow="horizontal"> extra为Image ) } } export const title = 'List' export const description = 'List Example' ``` ## API ### List Properties | Descrition | Type | Default | Version | -----------|------------|------|---------|---------| | renderHeader | list heder | (): void | | | | renderFooter | list footer | (): void | | | | styles | Semantic DOM style | [ListStyle](#liststyle-interface) | - | `5.2.1` | ### List.Item Properties | Descrition | Type | Default | Version | -----------|------------|------|---------|---------| | thumb | thumbnail on the left side of `List`(string type will be used to set img src) | String \| React.Element | | | | extra | extra content on the right side of `List` | String \| React.Element | | | | arrow | arrow direction, options: `horizontal`,`up`,`down`, `empty`; `empty` option may hide the dom | String | | | | align | vertical alignment of child elements,options: `top`,`middle`,`bottom` | String | `middle` | | | | onPress | callback is called when list is clicked | Same as [TouchableHighlightProps['onPress']](#touchablehighlightprops) | | | | multipleLine | multiple line | Boolean | `false` | | | wrap | Whether to wrap long texts, otherwise it will be hidden by default. | Boolean | `false` | | | styles | Semantic DOM style | [ListItemStyle](#listitemstyle-interface) | - | `5.2.1` | ### TouchableHighlightProps New in `5.2.1`. In addition, all properties of [TouchableHighlightProps](https://reactnative.dev/docs/touchablehighlight) are supported; when setting `onPress` props, it has a default touch style:
`{ underlayColor:'#dddddd', activeOpacity: 0.5 }` ### List.Item.Brief Brief infomation Properties | Descrition | Type | Default | Version | -----------|------------|------|---------|---------| | wrap | Whether to wrap long texts, otherwise it will be hidden by default. | Boolean | `false` | | | styles | Semantic DOM style | [BriefStyle](#briefstyle-interface) | - | `5.2.1` | ### ListStyle interface ```typescript interface ListStyle { List: ViewStyle Header: TextStyle Footer: TextStyle Body: ViewStyle BodyBottomLine: ViewStyle } ``` ### ListItemStyle interface ```typescript interface ListItemStyle { underlayColor: ViewStyle // ListItem is a TouchableHighlight Item: ViewStyle // ListItem wrap Line: ViewStyle // borderBottom Thumb: ImageStyle Content: TextStyle Extra: TextStyle Arrow: TextStyle // horizontal arrow ArrowV: TextStyle // up/down arrow multipleLine: ViewStyle multipleThumb: ImageStyle } ``` ### BriefStyle interface ```typescript interface BriefStyle { Brief: ViewStyle BriefText: TextStyle } ``` --- ## ListView Source: https://rn.mobile.ant.design/components/list-view.md # ListView Documentation please checkout https://github.com/gameboyVito/react-native-ultimate-listview ## Examples ```tsx import { ListView } from '@ant-design/react-native' import React from 'react' import { Text, View } from 'react-native' export default class BasicListExample extends React.Component { state = { layout: 'list', } sleep = (time: any) => new Promise((resolve) => setTimeout(() => resolve(''), time)) onFetch = async ( page = 1, startFetch: (arg0: string[], arg1: number) => void, abortFetch: () => void, ) => { try { //This is required to determinate whether the first loading list is all loaded. let pageLimit = 30 if (this.state.layout === 'grid') { pageLimit = 60 } const skip = (page - 1) * pageLimit //Generate dummy data let rowData = Array.from( { length: pageLimit }, (_, index) => `item -> ${index + skip}`, ) //Simulate the end of the list if there is no more data returned from the server if (page === 3) { rowData = [] } //Simulate the network loading in ES7 syntax (async/await) await this.sleep(2000) startFetch(rowData, pageLimit) } catch (err) { abortFetch() //manually stop the refresh or pagination if it encounters network error } } renderItem = (item: any) => { return ( {item} ) } render() { return ( `${this.state.layout} - ${item} - ${index}` } renderItem={this.renderItem} numColumns={this.state.layout === 'list' ? 1 : 3} /> ) } } export const title = 'ListView' export const description = 'ListView Example' ``` --- ## Modal Source: https://rn.mobile.ant.design/components/modal.md # Modal Use to show important information for the system, and ask for user feedback. eg: When deleting an important content, pop up a Modal for secondary confirmation. ### Rules - Use as few as possible. Modal will interrupt user operation, only use it at important situation. - Title should be concise, do not exceed 1 line; description should be concise and complete, generally no more than 2 lines. - Operation buttons are up to 3(vertical), generally 1-2(horizontal); [ActionSheet](/components/action-sheet) is preferred when there are more than 3 actions. - Generally put the most likely clicked button on the right side. In addition, the cancel button should always be on the left. ## Examples ```tsx import { Button, List, Modal, Provider, Switch, Toast, WhiteSpace, WingBlank, } from '@ant-design/react-native' import React from 'react' import { ScrollView, Text, View } from 'react-native' export default class BasicModalExample extends React.Component { constructor(props: any) { super(props) this.state = { visible: false, visible1: false, visible2: false, modalType: 'portal', } } onClose = () => { this.setState({ visible: false, }) } onClose1 = () => { this.setState({ visible1: false, }) } onClose2 = () => { this.setState({ visible2: false, }) } onButtonClick = () => { Modal.alert('Title', 'alert content', [ { text: 'Cancel', onPress: () => console.log('cancel'), style: 'cancel' }, { text: 'OK', onPress: () => console.log('ok') }, ]) } onButtonClickPromise = () => { Modal.alert('Title', 'promise button', [ { text: 'Cancel', onPress: () => { Toast.info('onPress promise resolve', 1) return new Promise((resolve) => { setTimeout(resolve, 1000) }) }, style: 'cancel', }, { text: 'Hold on', onPress: () => { Toast.info('onPress promise reject', 1) return new Promise((_, reject) => { setTimeout(reject, 1000) }) }, }, ]) } onButtonClick2 = () => { Modal.operation([ { text: '标为未读', onPress: () => console.log('标为未读被点击了') }, { text: '置顶聊天', onPress: () => console.log('置顶聊天被点击了') }, ]) } onButtonClick3 = () => { Modal.prompt( 'Login', 'Pleas input login information', (login: any, password: any) => console.log(`login: ${login}, password: ${password}`), 'login-password', '', ['Please input name', 'Please input password'], ) } onButtonClick4 = () => { Modal.prompt( 'Input password', 'password message', (password: any) => console.log(`password: ${password}`), 'secure-text', 'defaultValue', ) } onButtonClick5 = () => { Modal.prompt( 'Name', 'name message', (password: any) => console.log(`password: ${password}`), 'default', '', ['please input name'], ) } onButtonClick6 = () => { Modal.operation( [ { text: '标为未读', onPress: () => console.log('标为未读被点击了') }, { text: '置顶聊天', onPress: () => console.log('置顶聊天被点击了') }, ], () => { console.log('返回键点击') return false }, ) } render() { const footerButtons = [ { text: 'Cancel', onPress: () => console.log('cancel') }, { text: 'Ok', onPress: () => console.log('ok') }, ] return ( { this.setState({ modalType: val ? 'modal' : 'portal' }) }} checkedChildren="modal" unCheckedChildren="portal" /> }> 切换modalType `modalType='modal'`时将调用原生Modal{' '} Content... Content... Content... Content... Content... Content... ) } } ``` ## API ### Modal Properties | Descrition | Type | Default | Version -----------|------------|------|---------|---------| | visible | Determine whether a modal dialog is visible or not | Boolean | false | | | closable | Determine whether a close (x) button is visible or not | Boolean | false | | | maskClosable | Determine whether to close the modal dialog when clicked mask of it | Boolean | true | | | onClose | Callback for clicking close icon x or mask | (): void | - | | | transparent | transparent mode or full screen mode | Boolean | false | | | popup | popup mode | Boolean | false | | | animationDuration | Animation duration, in ms | Number | 300 | `5.3.0` | | animationType | Options: 'fade' / 'slide' | String | |fade | | modalType | The type of the popup.
When it is `'portal'`, it is inserted from the `` root node (default).
When it is `'modal'`, it is the same as [`react-native/Modal`](https://reactnative.dev/docs/modal) (used to get the current context).
When it is `'view'`, it is the same as `react-native/View` (used to nest popups in popups). | `'portal'`\| `'modal'` \| `'view'` | `'portal'` | `5.3.0` | | title | title | React.Element | - | | | footer | footer content | Array [{text, onPress}] | [] | | | onRequestClose | The `onRequestClose` callback is called when the user taps the hardware back button on Android or the menu button on Apple TV. Returns `true` to prevent `BackHandler` events when modal is open.| (): boolean | false | | | style | style same as `styles.innerContainer` | `ViewStyle` | - | | | styles | Semantic DOM style | [ModalStyle](#modalstyle-interface) | - | | ### ModalStyle interface ```typescript interface ModalStyle { container: ViewStyle // Set `z-index` wrap: ViewStyle // Set modal flex layout: `{justifyContent: 'center',alignItems: 'center'}` innerContainer: ViewStyle // modal content view, default: `{ widh:286 }` // modal content fields footer: ViewStyle header: TextStyle body: ViewStyle closeWrap: ViewStyle close: TextStyle buttonGroupH: ViewStyle buttonGroupV: ViewStyle buttonWrapH: ViewStyle buttonWrapV: ViewStyle buttonText: TextStyle // popup popupContainer: ViewStyle popupSlideUp: ViewStyle popupSlideDown: ViewStyle // operation operationContainer: ViewStyle operationBody: ViewStyle buttonTextOperation: TextStyle } ``` ### Modal.useModal() When you need using Context, you can use `contextHolder` which created by `Modal.useModal` to insert into children. Modal created by hooks will get all the context where `contextHolder` are. Created `modal` has the same creating function with [`Modal.method`](#static-method)(Static method). ```jsx const [modal, contextHolder] = Modal.useModal(); React.useEffect(() => { modal.alert( // ... ); }, []); return {contextHolder}; ``` ## Static method ### Modal.alert(title, message, actions?) Properties | Descrition | Type | Default -----------|------------|------|-------- | title | title | String or React.Element | - | | message | message | String or React.Element | - | | actions | button group, [{text, onPress, style}] | Array | - | | onBackHandler | Callback of the back key (not required), returns true to close modal, false to prevent modal from closing| (): boolean | 无 | ### Modal.prompt(title, message, callbackOrActions, type?, defaultValue?) Properties | Descrition | Type | Default -----------|------------|------|-------- | title | title | String or React.Element | - | | message | message | String or React.Element | - | | callbackOrActions | button group [{text, onPress}] or callback | Array or Function | - | | type | prompt style | String (`default`, `secure-text`, `login-password`)| `default` | | defaultValue | Default(input whick type is password is not supported) | String | - | | placeholders | ['', ''] | String[] | - | | onBackHandler | Callback of the back key (not required), returns true to close modal, false to prevent modal from closing| (): boolean | 无 | ### Modal.operation(actions?, onBackHandler?) Properties | Descrition | Type | Default -----------|------------|------|-------- | actions | button group, [{text, onPress, style}] | Array | - | | onBackHandler | Callback of the back key (not required), returns true to close modal, false to prevent modal from closing| (): boolean | 无 | ## FAQ ### How to close the static Modal.method()? You need to use `Portal.remove(key)` method; Take `Modal.alert` as an example ```jsx import { Modal, Portal } from '@ant-design/react-native' import { useRef } from 'react' function App() { const key = useRef() const onOpen = () => { key.current = Modal.alert({}) } const onClose = () => { // close the Modal.alert Portal.remove(key) } } ``` When using `Modal.useModal`, use the `modal.remove(key)` method: ```jsx import { Modal, Portal } from '@ant-design/react-native' import { useRef } from 'react' function App() { const [modal, contextHolder] = Modal.useModal(); const key = useRef() const onOpen = () => { key.current = modal.alert({}) } const onClose = () => { // close the modal.alert modal.remove(key) } return ( <> ... {contextHolder} ) } ``` ### Why I can not access context,redux,useRouter in `` or `Modal.xxx`? Rendering `` or calling Modal methods directly is dynamically inserted into the `` root node through `Portal.add` by default. At this time, its context is different from the context of the current code, so the context information cannot be obtained. When you need context info,
**1.** you can use `Modal.useModal` to get `modal` instance and `contextHolder` node. And put it in your children: ```tsx const [modal, contextHolder] = Modal.useModal(); // then call modal.confirm instead of Modal.confirm return ( {/* contextHolder is in Context1, which means modal will get context of Context1 */} {contextHolder} {/* contextHolder is out of Context2, which means modal will not get context of Context2 */} ); ``` **Note**: You must insert `contextHolder` into your children with hooks. You can use origin method if you do not need context connection. **2.** When using ``, by setting `modalType='modal'`, the **native Modal component** will be used internally to maintain the context: ```tsx ... ``` --- ## NoticeBar Source: https://rn.mobile.ant.design/components/notice-bar.md # NoticeBar Component to display a system message, event notice and etc. Which is under the navigation bar. ### Rules - Be used to attract user's attension, the importance level is lower than `Modal` and higher than `Toast`. - It can also achieve a lightweight marquee effect. ## Examples ```tsx import { Icon, List, NoticeBar, Picker, Provider, Slider, Switch, WhiteSpace, } from '@ant-design/react-native' import React, { useState } from 'react' import { ScrollView, Text } from 'react-native' export default function NoticeBarExample() { return ( {true && ( <> 默认 错误 信息 这条通知可以关闭 Notice: I can be a React component, multiple React components, or just some text. autoFill&spacing { console.log('onPress') }}> mode="link" } action={ }> 自定义图标 不再提示}> 自定义右侧功能区 Closable demo for `action`. )} ) } function ControlDemo() { const [play, setPlay] = useState(true) const [autoFill, setAutoFill] = useState(false) const [direction, setDirection] = useState<'left' | 'right' | 'up' | 'down'>( 'left', ) const [fps, setFps] = useState(40) return ( <> Notice: I can be a React component, multiple React components, or just some text. }> Play }> AutoFill setDirection(val[0] as any)}> Direction 速度fps: {fps} ) } ``` ## API | Properties | Descrition | Type | Default | Version | |------------|------------|------|---------|---------| | action | text which is used to replace right icon | `ReactNode` | - | | | children | The children rendered inside the marquee | `ReactNode` | - | | | icon | Set the icon at the start position | `ReactNode` | ``| | | marqueeProps | marquee params | [MarqueeProps](#marquee-props) | `{loop: false, leading: 500, trailing: 800, fps: 40}` | | | mode | Type of NoticeBar. Invalid when `action` is present | `closable`\|`link` | - | | | onClose | A callback function, can be executed when you click the `action` icon. Only valid in `mode="closable"` | `() => void` | - | `5.2.1` | | onPress | A callback function, can be executed when you click on the operating area | `() => void` | - | | | style | Container style | `StyleProp` | - | | | styles | Semantic DOM style | [NoticeBarStyle](#noticebarstyle-interface) | - | | - Theme color [theme.brand_error](https://github.com/ant-design/ant-design-mobile-rn/blob/master/components/style/themes/default.tsx#L35) = `#f4333c` ### Marquee props | Properties | Descrition | Type | Default | Version | |------------|------------|------|---------|---------| | autoFill | Whether to automatically fill blank space in the marquee with copies of the children or not | `Boolean` | false | `5.2.1` | | direction | The direction the marquee slides | `'left'` \| `'right'` \| `'up'` \| `'down'` | `'left'` | `5.2.2` add `'up'`&`'down'` | | fps | Speed calculated as pixels/second | `Number` | 40 | | | leading | Duration to delay the animation after first render, in millisecond | `Number` | 500 | | | loop | The number of times the marquee should loop, `true/0` is equivalent to infinite | `Boolean` \| `Number` | false | | | onFinish | A callback for when the marquee finishes scrolling and stops. Only calls if loop is non-zero or false. | `() => void` | - | `5.2.1` | | onCycleComplete | A callback for when the marquee finishes a loop. Does not call if maximum loops are reached (use onFinish instead). | `() => void` | - | `5.2.1` | | play | Whether to play or pause the marquee | `Boolean` | true | `5.2.1` | | spacing | Spacing between repeting elements, valid when `autoFill={true}` | `Number` | 0 | `5.2.1` | | style | The marquee Text style | `TextStyle` | - | | | trailing | Duration to delay the animation after previous loop, valid when `autoFill={false}`, in millisecond | `Number` | 800 | | | wrapStyle | Marquee wrap view style | `ViewStyle` | - | | > Design Reference: [https://github.com/justin-chu/react-fast-marquee](https://github.com/justin-chu/react-fast-marquee), can be used as a marquee component alone ```jsx // New in 5.2.2 import { Marquee } from '@ant-design/react-native' ``` ## NoticeBarStyle interface `5.2.1`refactored the styles ```ts interface NoticeBarStyle { container: ViewStyle, // Outermost container style, default: {minHeight: 36(theme.notice_bar_height)} font: TextStyle, // Font style, default: {color: #f4333c(theme.brand_error)} background: ViewStyle, // Background color, default: {backgroundColor: #fffada} marquee: TextStyle, // marquee font style iconWrap: ViewStyle, // left icon wrap actionWrap: ViewStyle, // right action wrap close: ViewStyle, // mode="closeable" icon link: ViewStyle // mode="link" icon } ``` ## Ref New in `5.2.1`. Ref to MarqueeActions. | Properties | Descrition | Type| |-----|------|------| | play | Start the marquee text rolling | `() => void` | | pause | Pause the marquee text | `() => void` | | stop | Return the marquee text to the original position | `() => void` | --- ## Pagination Source: https://rn.mobile.ant.design/components/pagination.md # Pagination A long list can be divided into several pages by `Pagination`, and only one page will be loaded at a time. ### Rule - When it will take a long time to load/render all items. ## Examples ```tsx import { Pagination, WhiteSpace, WingBlank } from '@ant-design/react-native' import React from 'react' const locale = { prevText: '上一步', nextText: '下一步', } export default class BasicPaginationExample extends React.Component { render() { return ( ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | mode | the mode of `Pagination` which can be one of `button`,`number`,`pointer` | string | `button` | | current | current page index | number | 1 | | total | total number of data | number | 0 | | simple | whether to hide number | boolean | false | | disabled | whether is disabled | boolean | false | | locale | [i18n](/components/locale-provider/) setting, you can override the configuration of the global `LocaleProvider | Object:{prevText, nextText} | | | onChange | invoked with the new index when the value changes. | (index: Number): void | | --- ## Picker Source: https://rn.mobile.ant.design/components/picker.md # Picker Choose from a set of data, e.g. Country choice. ### Rules - Try to use Picker to help users complete the input, to avoid the user through the keyboard directly input. - DatePicker is Picker's specific pattern. ## Examples ```tsx import { Button, List, Picker, PickerValue, PickerValueExtend, Provider, } from '@ant-design/react-native' import { district } from 'antd-mobile-demo-data' import React, { useState } from 'react' import { Text, TouchableOpacity, View } from 'react-native' const CustomChildren = (props: any) => ( {props.children} {props.extra} ) // visible用法 function BasicDemo() { const [visible, setVisible] = useState(false) const [value, setValue] = useState([]) const [extend, setExtend] = useState() return ( {/* extend渲染所选值 */} {extend?.items?.map((item: any) => item.label).join(',') || ' 未选择'} {/* visible控制显示/隐藏 */} { setVisible(v) }} visible={visible} value={value} onOk={(v: PickerValue[], ext: PickerValueExtend) => { setValue(v) setExtend(ext) }} /> ) } export default class PopupExample extends React.Component { constructor(props: any) { super(props) this.state = { data: [], value: [], pickerValue: [], } } onPress = () => { setTimeout(() => { this.setState({ data: district, }) }, 500) } onChange = (value: any) => { this.setState({ value }) } render() { return ( 省市选择 省市选择(异步加载) this.setState({ pickerValue: v })} onOk={(v: any) => this.setState({ pickerValue: v })}> Customized children ) } } ``` ## API ### Props ```ts type PickerColumnItem = { label: string | ReactNode value: string | number key?: string | number children?: PickerColumnItem[] } type PickerColumn = PickerColumnItem[] type PickerValue = string | number type PickerValueExtend = { columns: PickerColumn[] items: (PickerColumnItem | undefined)[] } ``` Properties | Descrition | Type | Default | Version -----------|------------|------|--------|-------- | data | data source | `PickerColumn` / `PickerColumn[]` | - | | | value | Selected options | `PickerValue[]` | - | | | defaultValue | Default selected options | `PickerValue[]` | - | | | cascade | whether cascade
child cascade get from `data[].children` | Boolean | `true` | | | cols | col numbers | Number | `3` | | | onChange | selected callback function, can use [Form](/components/form) | `(value: PickerValue[], extend: PickerValueExtend) => void` | - | | | onPickerChange | trigger on each column of selected data is changed | `(value: PickerValue[], index: number) => void` | - | | | onVisibleChange | visible state change callback | `(visible: bool): void` | - | | | renderLabel | The function to custom rendering the label shown on a column | `(item: PickerColumnItem, itemIndex: number, colIndex: number) => ReactNode` | `(item) => item.label` | `5.2.2` | | locale | international, can override the configuration of the global [Provider](/components/provider)'s `locale` | Object: Object: {okText, dismissText, extra} | - | | | title | title | ReactNode | - | | | okText | ok text | String | `确定` | | | dismissText | dismiss text | String | `取消` | | | onOk | handler called when click ok | `(value: PickerValue[], extend: PickerValueExtend) => void` | - | | | onDismiss | handler called when click cancel | (): void | - | | | okButtonProps | The ok button props | [TouchableHighlightProps](https://reactnative.dev/docs/touchablehighlight) | `{ activeOpacity:1, underlayColor:'#ddd' }` | `5.1.3` | | dismissButtonProps | The dismiss button props | [TouchableHighlightProps](https://reactnative.dev/docs/touchablehighlight) | `{ activeOpacity:1, underlayColor:'#ddd' }` | `5.1.3` | | visible | Whether to show or hide the Picker | Boolean | - | | | loading | Should the Picker displays as loading state | Boolean | - | `5.1.0` | | loadingContent | The loading content displayed in loading state | ReactNode | - | `5.1.0` | | indicatorStyle | style of default Indicator | Object | - | | ### Custom Style Properties | Descrition | Type | Default | Version -----------|------------|------|---------|--------- | style | style | `StyleProp` | - | | | styles | inner component styles | [PickerStyle](#pickerstyle-interface) & [PickerViewStyle](/components/picker-view/#pickerviewstyle-interface) | - | `5.1.0`refactored | | itemStyle| style to apply to each of the item labels | `StyleProp` | - | | | itemHeight | Height of option item, calculated by `numberOfLines` when without value; `itemStyle` was not allowed to set `{height}` | Number | - | | | numberOfLines | Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number | Number | `1` | | ### PickerStyle interface ```jsx interface PickerStyle extends Partial { // modal style modal: ViewStyle container: ViewStyle header: ViewStyle headerItem: ViewStyle actionText: TextStyle title: TextStyle okText: TextStyle dismissText: TextStyle } ``` #### Mask View New in `5.1.0`. Support custom mask style, such as using the gradient component ``. Default is white translucency. Properties | Descrition | Type | Default -----------|------------|------|-------- | renderMaskTop | The function to custom rendering the mask top half view | `()=> ReactNode` | `` | | renderMaskBottom | The function to custom rendering the mask bottom half view | `()=> ReactNode` | `` | - Theme color [theme.fill_base](https://github.com/ant-design/ant-design-mobile-rn/blob/master/components/style/themes/default.tsx#L24) = `#ffffff` ### Custom Children Picker's children is best to [List.Item](/components/list/#List.Item), if not, need to be a custom component (the `onPress`/`extra` props need to be handled in the component): Properties | Descrition | Type | Default | Version | -----------|------------|------|--------|-------- | children| usually `List.Item` | `ReactNode`/`({disabled, extra, value, toggle})=>ReactNode` | - | `5.2.1` add function as Children | | extra | Picker's children `extra` prop, display when no `value`(Similar to a placeholder) | String | `please select` | | | format | a function that formats the selected value | (labels: string[]): any | `(labels) => { return labels.join(','); } ` | | | triggerType | Press event name | String | `onPress` | | | disabled | set disabled | Boolean | `false` | | ### PickerActions Properties | Descrition | Type -----------|------------|----- | close | Close Picker | `() => void` | | open | Open Picker | `() => void` | | toggle | Toggle the visible state of Picker | `() => void` | ### Ref Same as PickerActions ## FAQ ### Why is the Picker hidden when it popup in the native Modal? By default, `` is dynamically inserted into the `` root node via `Portal.add`, and the zIndex level of the native Modal is above everything, including its root node. So if you must use the `` component in the native Modal, you can set `modalType='modal'` to keep it at the same level as the native Modal. ```tsx import {Modal} from 'react-native'; import {Picker} from '@ant-design/react-native'; ... 省市选择 ``` --- ## PickerView Source: https://rn.mobile.ant.design/components/picker-view.md # PickerView PickerView's functions like Picker, but it is rendered directly in the area instead of the pop-up window. ## Examples ```tsx import { List, PickerView } from '@ant-design/react-native' import React from 'react' import { ScrollView } from 'react-native' const basicColumns = [ [ { label: '周一', value: 'Mon' }, { label: '周二', value: 'Tues' }, { label: '周三', value: 'Wed' }, { label: '周四', value: 'Thur' }, { label: '周五', value: 'Fri' }, ], [ { label: '上午', value: 'am' }, { label: '下午', value: 'pm' }, ], ] export default class PickerViewExample extends React.Component { state = { value: undefined, } onChange = (value: any) => { this.setState({ value, }) } render() { return ( ) } } ``` ## API ### Props Properties | Descrition | Type | Default | Version -----------|------------|------|---------|--------- | data | data source | `PickerColumn` / `PickerColumn[]` | - | | | value | Selected options | `PickerValue[]` | - | | | defaultValue | Default selected options | `PickerValue[]` | - | | | cascade | whether cascade
child cascade get from `data[].children` | Boolean | `true` | | | cols | col numbers | Number | `3` | | | onChange | selected callback function, can use [Form](/components/form) | `(value: PickerValue[], extend: PickerValueExtend) => void` | - | | | renderLabel | The function to custom rendering the label shown on a column | `(item: PickerColumnItem, itemIndex: number, colIndex: number) => ReactNode` | `(item) => item.label` | `5.2.2` | | loading | Should the Picker displays as loading state | Boolean | - | `5.1.0` | | loadingContent | The loading content displayed in loading state | ReactNode | `` | `5.1.0` | | indicatorStyle | style of default Indicator | Object | - | | For the type definition of `PickerColumnItem` `PickerColumn` `PickerValue` `PickerValueExtend`, please refer to the document of [Picker](/components/picker/). ### Custom Style Properties | Descrition | Type | Default | Version -----------|------------|------|---------|--------- | style | style | `StyleProp` | - | | | styles | Semantic DOM style | [PickerViewStyle](#pickerviewstyle-interface) | - | `5.1.0`refactored | | itemStyle| style to apply to each of the item labels | `StyleProp` | - | | | itemHeight | Height of option item, calculated by `numberOfLines` when without value; `itemStyle` was not allowed to set `{height}` | Number | - | | | numberOfLines | Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number | Number | `1` | | #### PickerViewStyle interface ```jsx interface PickerViewStyle { wrappper: ViewStyle wheelWrapper: ViewStyle // item style itemWrap: ViewStyle itemStyle: TextStyle itemActiveStyle: TextStyle // New in `5.2.2` // mask view mask: ViewStyle maskTop: ViewStyle maskMiddle: ViewStyle maskBottom: ViewStyle } ``` #### Mask View New in `5.1.0`. Support custom mask style, such as using the gradient component ``. Default is white translucency. Properties | Descrition | Type | Default -----------|------------|------|-------- | renderMaskTop | The function to custom rendering the mask top half view | `()=> ReactNode` | `` | | renderMaskBottom | The function to custom rendering the mask bottom half view | `()=> ReactNode` | `` | - Theme color [theme.fill_base](https://github.com/ant-design/ant-design-mobile-rn/blob/master/components/style/themes/default.tsx#L24) = `#ffffff` ## FAQ ### On the Android platform, when using `PickerView` nested in `ScrollView`, the Picker Item cannot slide. What should I do? Support in `5.1.3`. Set the `nestedScrollEnabled` property of `ScrollView` to `true`. ```jsx ... ``` --- ## Popover Source: https://rn.mobile.ant.design/components/popover.md # Popover > This package has been deprecated in `5.2.1`, recommend [components/Tooltip](/components/tooltip) After clicking on a control or an area, a Popover menu appears for doing more. If set mask prop, it is recommended to exit by clicking on any of the mask layers. ## Examples ```tsx import { List, Popover } from '@ant-design/react-native' import React from 'react' import { Easing, StyleSheet, Text, View } from 'react-native' const Item = Popover.Item export default class PopoverExample extends React.Component { constructor(props: any) { super(props) this.state = { selected: '', } } onSelect = (value: any) => { this.setState({ // visible: false, selected: value, }) } render() { let overlay = [1, 2, 3].map((i, index) => ( option {i} )) overlay = overlay.concat([ disabled opt , 关闭 , ]) return ( {[1, 2, 3, 4, 5, 6, 7, 8].map((item) => this.renderList(overlay, item), )} 自定义组件 x } renderOverlayComponent={(nodes) => ( 我是自定义组件title {nodes} )}> 自定义组件 (show ? Easing.in(Easing.ease) : Easing.step0)}> 自定义动画 如果你设置了 placement 属性请确保你的内容够位置显示,默认是 auto 自动计算位置 {['left', 'right', 'top', 'bottom'].map((p) => ( 自定义组件 {p} } placement={p as any}> {p} ))} ) } private renderList(overlay: React.ReactNode[], key: number) { return ( this.setState({ [`selected${key}`]: v, }) }> 菜单 }> 选择了:{this.state[`selected${key}`]} ) } } const styles = StyleSheet.create({ triggerStyle: { paddingHorizontal: 6, }, }) export const title = 'Popover' export const description = 'Popover example' ``` ## API ### Popover Properties | Descrition | Type | Default -----------|------------|------|-------- | overlay | Popup layer content | ReactNode | - | | placement | How to position the popover | 'top | right | bottom | left | auto' | auto | | onSelect | when an option is selected | (value: any): void | - | | triggerStyle | trigger style | ViewStyle | - | | renderOverlayComponent | A function that renders takes in the MenuOptions element and renders a container element that contains the options. Default function wraps options with a `ScrollView`. e.g. `(nodes) => {nodes}` | (node: React.ReactNode) => React.ReactNode | - | | duration | Animation duration | number | 300 | | easing | Function that returns easing function for show or hide animation, depending on `show` argument | (show: boolean) => (value: number) => number | show => show ? Easing.out(Easing.back(1.70158)) : Easing.inOut(Easing.quad) | | useNativeDriver | Defines if animations should use native driver | boolean | false | | onDismiss | Callback to be fired after the popup closes | function | - | ### Popover.Item Properties | Descrition | Type | Default -----------|------------|------|-------- | disabled | set disabled | Boolean | false | | style | item style | ViewStyle | - | | value | can be used as the selected option ID | any | - | --- ## Progress Source: https://rn.mobile.ant.design/components/progress.md # Progress Progress Bar to indicate your task's progress. ### Rules - When you need a accurate progress,otherwise you should use ActivityIndicator. - Hide the unfilled part when used with NavBar for better visual feeling. ## Examples ```tsx import { Button, Progress, WhiteSpace } from '@ant-design/react-native' import React from 'react' import { Text, View, ViewStyle } from 'react-native' export default class BasicProgressExample extends React.Component { constructor(props: any) { super(props) this.state = { percent: 40, } } onAdd = () => { let p = this.state.percent + 10 if (this.state.percent >= 100) { p = 0 } this.setState({ percent: p }) } render() { const style = { marginTop: 80, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', } return ( {this.state.percent}% ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- percent | percent value of progress | number | 0 position | position of progress bar, optional:`fixed` `normal` | string | `fixed` unfilled | whether to fill unfinished part of progress | boolean | true style | the style of container | object | {} barStyle | the style of bar | object | {} --- ## Provider Source: https://rn.mobile.ant.design/components/provider.md # Provider `Provider` provides a uniform localization support for built-in text of components. ## When to use - You want to use other languages than `Chinese` - You want to change the default theme color. - You want to add vibration feedback to built-in component. - You want to use the `Portal component`. ## Examples ```tsx import { DatePicker, List, Pagination, Picker, Provider, SearchBar, WhiteSpace, WingBlank, } from '@ant-design/react-native' import enUS from '@ant-design/react-native/lib/locale-provider/en_US' import esES from '@ant-design/react-native/lib/locale-provider/es_ES' import faIR from '@ant-design/react-native/lib/locale-provider/fa_IR' import koKR from '@ant-design/react-native/lib/locale-provider/ko_KR' import ptBR from '@ant-design/react-native/lib/locale-provider/pt_BR' import ruRU from '@ant-design/react-native/lib/locale-provider/ru_RU' import svSE from '@ant-design/react-native/lib/locale-provider/sv_SE' import zhCN from '@ant-design/react-native/lib/locale-provider/zh_CN' import React from 'react' import { View } from 'react-native' const maxDate = new Date(2018, 11, 3, 22, 0) const minDate = new Date(2015, 7, 6, 8, 30) const seasons = [ [ { label: '2013', value: '2013', }, { label: '2014', value: '2014', }, ], [ { label: '春', value: '春', }, { label: '夏', value: '夏', }, ], ] const Page = React.memo(() => ( DatePicker Picker )) export default class LocaleProviderExample extends React.Component { constructor(props: any) { super(props) this.state = { locale: 'English', } } onChange = (value: any) => { this.setState({ locale: value[0], }) } render() { const { locale } = this.state const languages: Array = [ { value: '中国', label: '中国', language: zhCN, }, { value: 'English', label: 'English', language: enUS, }, { value: 'Русский', label: 'Русский', language: ruRU, }, { value: 'Español', label: 'Español', language: esES, }, { value: 'Português - BR', label: 'Português - BR', language: ptBR, }, { value: 'Sverige', label: 'Sverige', language: svSE, }, { value: 'Persian', label: 'Persian', language: faIR, }, { value: '한국', label: '한국', language: koKR, }, ] const currentLocale = languages.find( (item) => item.value === locale, ).language return ( Choose language ) } } ``` ### Portal Component `ActionSheet` `Modal` `Picker` `Toast` `ToolTip` belongs to Portal component; To use these components, you must wrap your root component (usually in App.js) with `Provider` component. ## API | Property | Description | Type | Default | Version | | -----|-----|-----|-------|------| | locale | Language package setting(`The default language is Chinese`),
you can find the packages in this path: [`@ant-design/react-native/lib/locale-provider/`](https://github.com/ant-design/ant-design-mobile-rn/blob/master/components/locale-provider) | [Locale](https://github.com/ant-design/ant-design-mobile-rn/blob/master/components/locale-provider/index.tsx#L4) | - | | | theme | Theme customization, you can override some or all variables as needed | [Theme](https://github.com/ant-design/ant-design-mobile-rn/blob/master/components/style/themes/default.tsx) | - | | | onHaptics | Set the vibration engine. This method will be triggered when the built-in component needs vibration feedback. | `(componentName: 'picker' | 'stepper' | 'slider' | 'switch') => void` | - | `5.2.1` | | isRTL | Whether use Right-to-Left (RTL) languages.
Currently only applies to `` | `Boolean` | `I18nManager.isRTL` | `5.2.1` | ## FAQ ### How do I customize my theme? For example: Modifying the following theme variables has a relatively large impact ```jsx background color primary_button_fill_tap: palette[3], // }> Disabled Disabled Use Ant Design Component Use Ant Design Component A B C D Option A Option B Option C More... ) } } const plainOptions = ['Apple', 'Pear', 'Orange'] const options = [ { label: 'Apple', value: 'Apple' }, { label: 'Pear', value: 'Pear' }, { label: 'Orange', value: 'Orange' }, ] const optionsWithDisabled = [ { label: 'Apple', value: 'Apple' }, { label: 'Pear', value: 'Pear' }, { label: 'Orange', value: 'Orange', disabled: true }, ] class RadioGroupExample extends React.Component { state = { value1: 'Apple', value2: 'Apple', value3: 'Apple', } onChange1 = (e: EventRadioGroup) => { console.log('radio1 checked', e.target.value) this.setState({ value1: e.target.value, }) } onChange2 = (e: EventRadioGroup) => { console.log('radio2 checked', e.target.value) this.setState({ value2: e.target.value, }) } onChange3 = (e: EventRadioGroup) => { console.log('radio3 checked', e.target.value) this.setState({ value3: e.target.value, }) } render() { const { value1, value2, value3 } = this.state return ( <> ) } } ``` ## API ### Type ```ts type RadioValue = string | number ``` ### Radio Properties | Descrition | Type | Default -----------|------------|------|-------- | defaultChecked | the initial checked state | Boolean | - | | checked | to set the current checked state | Boolean | - | | disabled | whether disabled | Boolean | false | | onChange | a callback function, can be executed when the checked state changes | (e: { target: { checked: boolean } }) => void | - | | value | Value is carrying identification, used in `Group` mode | `RadioValue` | - | ### Radio.RadioItem The encapsulation about `Radio` based on `List.Item`, the property `extra` of `List.Item` will be passed to `Radio`, while other properties remain the same. Other APIs are identical with `Radio`. ### Radio.Group `v5.0.0` Radio group can wrap a group of `Radio`。 ```ts type Event = { target: { value: RadioValue } } ``` Properties | Descrition | Type | Default ----|-----|------|------ | defaultValue | Default selected value | `RadioValue` | - | | disabled | Disable all radio buttons | Boolean | false | | options | Set children optional | `string[]` \| `number[]` \| `Array<{ label: string value: string disabled?: boolean }>` | - | | value | Used for setting the currently selected value | `RadioValue` | - | | onChange | The callback function that is triggered when the state changes | (e: `Event`) => void | - | --- ## Result Source: https://rn.mobile.ant.design/components/result.md # Result Result page contains feedback like illustrations, icons and text. ### Rules - Use for significant feedback like payment success or network failure. - Improve brand value with beautiful illustrations. - Provide obvious operation point for error type result page, eg: reload page. ## Examples ```tsx import { Result } from '@ant-design/react-native' import React from 'react' import { Image, ScrollView, Text } from 'react-native' export default class ResultExample extends React.Component { render() { return ( URI 图片 Image source Image element } title="验证成功" message={所提交内容已成功完成验证} /> 含 button 操作 } title="验证成功" message="所提交内容已成功完成验证" buttonText="完成" buttonType="primary" onButtonClick={(e: any) => alert(e.toString())} /> ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- imgUrl | image url | string / Image Source(rn) | - img | image node (could be `` or ``), which will override `imgUrl` | ReactNode | - title | title of result page | ReactNode | - message | message text of result page | ReactNode | - buttonText | text of built-in button | string | - buttonType | type of built-in button | string | - onButtonClick | callback of clicking built-in button | (e: Object): void | - --- ## SearchBar Source: https://rn.mobile.ant.design/components/search-bar.md # SearchBar Normally located below NavBar, the activation status is exited by the Cancel button. ### Rules - Should fill some text in placeholder to remind the user to enter the relevant content, such as: "双11特卖". - Below the SearchBar, you can provide useful labels copy to help users complete the input directly by clicking, such as: List some of the most recent search keywords. ## Examples ```tsx import { SearchBar } from '@ant-design/react-native' import React from 'react' import { Alert, View } from 'react-native' export default class SearchBarDemo extends React.Component { state = { value: '美食', } onChange = (value: any) => { this.setState({ value }) } clear = () => { this.setState({ value: '' }) } render() { return ( Alert.alert(value)} onCancel={this.clear} onChange={this.onChange} showCancelButton /> ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | defaultValue | the uncontrolled default value | String | | | value | the controlled current value | String | | | placeholder | placeholder | String | | | onSubmit | submit event (click the enter on the keyboard) | (val: string): void | | | onChange | change event callback | (val: string): void | | | onFocus | focus event callback | (): void | | | onBlur | blur event callback | (): void | | | onCancel | Click the `Cancel` button to trigger (The text of the input box is no longer automatically cleared) | (val: string): void | | | showCancelButton | Whether the `Cancel` button is always displayed | bool | `false` | | cancelText | Customize the text of the `Cancel` button | String | `取消` | | disabled | Set disabled | bool | `false` | Note: RN version more API please refer to [http://facebook.github.io/react-native/docs/textinput.html](http://facebook.github.io/react-native/docs/textinput.html) --- ## SegmentedControl Source: https://rn.mobile.ant.design/components/segmented-control.md # SegmentedControl Deprecated since `5.2.1`. Please use [@react-native-community/segmented-control](https://github.com/react-native-community/segmented-control#usage) instead. --- ## Slider Source: https://rn.mobile.ant.design/components/slider.md # Slider A Slider component for selecting particular value in range, eg: controls the display brightness of the screen. ### Rule - By default, the minimum value in the left and maximum value in the right of `Slider` . - Generally `Slider` is positioned horizontally. ## Examples ```tsx import { List, Provider, Slider, Switch, Toast } from '@ant-design/react-native' import React, { useEffect, useState } from 'react' import { ScrollView } from 'react-native' export default function StepperExample() { useEffect(() => { Toast.config({ stackable: false }) }, []) const [disabledStep, setDisabledStep] = useState(false) const [tapToSeek, setTapToSeek] = useState(true) const marks = { 0: 0, // 20: 20, 40: 40, 60: '', 80: 80, 100: 100, } const toastValue = (value: number | [number, number]) => { let text = '' if (typeof value === 'number') { text = `${value}` } else { text = `[${value.join(',')}]` } Toast.show({ content: `当前选中值为:${text}`, position: 'top' }) } return ( { setDisabledStep(val) }} /> }> Disabled Step 是否禁用步距;禁用后`onChange`将返回带有小数点的值 { setTapToSeek(val) }} /> }> Tap To Seek 是否允许点击滑块轨道来设置slider值 true} onTouchStart={(e) => e.stopPropagation()}> console.log('onSlidingStart', { val, index }) } onSlidingComplete={(val, index) => console.log('onSlidingComplete', { val, index }) } /> ) } ``` ## API | Properties | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | defaultValue | Default value | `number` \|
`[number, number]` | `range ? [0, 0] : 0` | | | disabled | Whether disabled | `boolean` | `false` | | | disabledStep | Whether disabled step; if `true`, `onChange` will return a value with a decimal point | `boolean` | `false` | `5.3.0` | | icon | The thumb icon of slider | `ReactNode` | - | | | marks | Tick marks | `{ [key: number]: React.ReactNode }` | - | `5.2.1` | | max | Max value | `number` | `100` | | | min | Min value | `number` | `0` | | | onAfterChange | Consistent with the trigger timing of `touchend`, pass the current value as a parameter | `(value: number | [number, number]) => void` | - | | | onChange | Triggered when the slider is dragged, and the current dragged value is passed in as a parameter | `(value: number | [number, number]) => void` | - | | | onSlidingStart | Callback that is called when the user picks up the slider.
The initial value is passed as an argument to the callback handler. | `(value: number | [number, number], index: number) => void` | - | `5.3.0` | | onSlidingComplete | Callback that is called when the user releases the slider, regardless if the value has changed.
The current value is passed as an argument to the callback handler. | `(value: number | [number, number], index: number) => void` | - | `5.3.0` | | popover | Whether to display the popover when dragging. Support passing in function to customize the rendering content. | `boolean | ((value: number) => ReactNode)` | `false` | `5.2.1` | | residentPopover | Whether the `popover` is permanently displayed , this attribute takes effect when `popover` exists | `boolean ` | `false` | `5.2.1` | | range | Whether it is a double sliders | `boolean` | `false` | `5.2.1` | | step | Step distance, the value must be greater than `0`, and `(max-min)` can be divisible by `step`. When `marks` is not null, the configuration of `step` is invalid | `number` | `1` | `5.2.1` | | style | Container style | `StyleProp` | - | | | styles | Semantic DOM style | [SliderStyle](#sliderstyle-interface) | - | `5.2.1` | | tapToSeek | Permits tapping on the slider track to set the thumb icon position. | `boolean` | `true` | `5.3.0` | | ticks | Whether to display the scale | `boolean` | `false` | `5.2.1` | | value | Current value | `number` \|
`[number, number]` | - | | > The returned `value` format is `[number, number]` when `range={true}`, otherwise it is `number`. ### SliderStyle interface ```typescript interface SliderStyle { // Same as `style` slider: ViewStyle // belongs to PanGesture area when `range=false` disabled: ViewStyle // Track trackContianer: ViewStyle // track container track: ViewStyle // track line fill: ViewStyle // Filled portion of the track line // Track button wrap + shadow style thumb: ViewStyle // Tick ticks: ViewStyle tick: ViewStyle tickActive: ViewStyle // Mark within the tick mark: ViewStyle markText: TextStyle } ``` --- ## Stepper Source: https://rn.mobile.ant.design/components/stepper.md # Stepper `Stepper` can be used to increase or decrease value step by step. ### Rule - When you want to make small adjustments to the value, you can use `Stepper`. eg: Adjust the annual return from 4.00% to 4.05%. ## Examples ```tsx import { List, Provider, Stepper, Toast } from '@ant-design/react-native' import React from 'react' import { KeyboardAvoidingView, Platform, ScrollView } from 'react-native' export default function StepperExample() { return ( { console.log(value) }} /> }> 基础用法 }> 步长设置 }> 限制输入范围 }> 格式化到一位小数 `$ ${value}`} parser={(text) => parseFloat(text.replace('$', ''))} onChange={(value) => { console.log(value, typeof value) }} /> }> 自定义格式 }>禁用状态 }>输入框只读状态 { Toast.info('获得焦点') }} onBlur={() => { Toast.info('失去焦点') }} /> }> 获得/失去焦点 { console.log(value) }} /> }> 允许清空 }> 自定义样式 ) } const StringModeExample = () => { const [value, setValue] = React.useState('9999999999999999') return ( ) } ``` ## API | Name | Description | Type | Default | Version | | --- | --- | --- | --- | --- | | allowEmpty | Whether to allow empty content. | `boolean` | `false` | | defaultValue | Default value | `number \| null` | `0` | | digits | Format to a fixed number of digits after the decimal point, set to `0` means format to integer. Will use `formatter` as display value when configured | `number` | - | 5.2.1 | | disabled | Whether to disabled Stepper | `boolean` | `false` | | formatter | Format value in input | `(value?: number) => string` | - | 5.2.1 | | inputStyle | TextInput style | `StyleProp` | - | | max | Max value | `number` | - | | min | Min value | `number` | - | | minusButtonProps | The minus button props | [TouchableHighlightProps](https://reactnative.dev/docs/touchablehighlight) | `{ activeOpacity:1, underlayColor:'#ddd', children: -, delayLongPress:500 }` | 5.2.1 | | plusButtonProps | The plus button props | [TouchableHighlightProps](https://reactnative.dev/docs/touchablehighlight) | `{ activeOpacity:1, underlayColor:'#ddd', children: +, delayLongPress:500 }` | 5.2.1 | | onChange | Callback when value is changed | `(value: number \| null) => void` | - | | parser | Parse input text into number which should work with `formatter` | `(text: string) => number` | - | 5.2.1 | | step | The value to increase or decrease each time, can be a decimal | `number` | `1` | | stringMode | Set value as string to support high precision decimals. Will set `defaultValue`,`value`, `min`, `max`, `onChange` to `string` type | `boolean` | `false` | 5.2.1 | | styles | Semantic DOM style | [StepperStyle](#stepperstyle-interface) | - | 5.2.1 | | value | Current number, controlled value | `number \| null` | - | - New in `5.2.1`. In addition, all properties of react-native [TextInput](http://facebook.github.io/react-native/docs/textinput.html) are supported, eg: **`readOnly`** **`onFocus`** **`onBlur`** - New in `5.2.1`. Support **Long Press To Trigger** increment or decrement; customizable execution timing: `plusButtonProps={{ delayLongPress: 500 }}`. - When `allowEmpty` is `true`, the `value` parameter of `onChange` may be **`null`**, please pay attention when using it. ### StepperStyle interface `5.2.1`refactored the styles ```typescript export interface StepperStyle extends Partial { // extends InputStyle container: ViewStyle input: ViewStyle prefix: ViewStyle // for minus button suffix: ViewStyle // for plus button // StepperStyle inputDisabled: TextStyle stepWrap: ViewStyle // step button wrap stepText: TextStyle // step button text stepDisabled: ViewStyle // step button disabled disabledStepTextColor: TextStyle } ``` ## Ref Same as [component/Input](/components/input#ref) --- ## Steps Source: https://rn.mobile.ant.design/components/steps.md # Steps Steps is typically used for displaying the progress of a task, or guiding users through the steps of a complex flow. ### Rules - Suitable for step-by-step and long-lasting task, e.g. the process of transfer accounts. If the task is continuous and short, such as opening a page, component `Progress` will fit better. - When the task is complicated or has a certain sequence in the series of subtasks, we can decompose it into several steps to make things easier, e.g. register new account. ## Examples ```tsx import { Icon, Steps, WingBlank } from '@ant-design/react-native' import React from 'react' import { ScrollView, Text, View } from 'react-native' const Step = Steps.Step export default class BasicTimelineExample extends React.Component { constructor(props: any) { super(props) this.state = { steps1: [ { title: 'Finished', description: 'This is description' }, { title: 'In Progress', description: 'This is description' }, { title: 'Waiting', description: 'This is description' }, ], steps2: [ { title: 'Finished', description: 'This is description', status: 'finish', }, { title: 'In Progress', description: 'This is description', status: 'process', }, { title: 'Waiting', description: 'This is description', status: 'error', }, { title: 'Waiting', description: 'This is description', status: 'wait', }, ], } } render() { return ( {this.state.steps1.map((item: any, index: any) => ( title:{item.title} } status={item.status} /> ))}
{this.state.steps1.map((item: any, index: any) => ( title:{item.title} } description={ desc:{item.description} } status={item.status} /> ))}
{this.state.steps2.map((item: any, index: any) => ( ))} {this.state.steps1.map((item: any, index: any) => ( ))} {this.state.steps2.map((item: any, index: any) => ( ))} } /> { let icon if (starting) { icon = } else if (waiting) { icon = } else if (error) { icon = } return icon }} /> { let icon if (starting) { icon = } else if (waiting) { icon = } else if (error) { icon = } return icon }} /> { let icon if (starting) { icon = } else if (waiting) { icon = } else if (error) { icon = } return icon }} /> { let icon if (starting) { icon = } else if (waiting) { icon = } else if (error) { icon = } return icon }} /> ) } } ``` ## API ```jsx ``` ### Steps The Steps container. | Properties | Descrition | Type | Default | | ---------- | -------------------------------------------------------------------------------------------------- | --------------------------------- | ---------- | | current | To set the current step, counting from 0. You can overwrite this state by using `status` of `Step` | number | `0` | | size | To specify the size of the step bar, a smaller size can be achieved by setting it to `small` | string | - | | direction | To specify the direction of the step bar(now only support `vertical` for react-native) | Enum { 'vertical', 'horizontal' } | `vertical` | ### Steps.Step A single step used as child component of the Step. | Properties | Descrition | Type | Default | | ----------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------- | | status | To specify the status. It will be automatically set by `current` of `Steps` if not configured. | Enum { 'wait', 'process', 'finish', 'error' } | `wait` | | title | Title of the step | React.Element | - | | description | Detail of the step(optional property) | React.Element | - | | icon | Icon of the step(optional property) | object/React.Element | - | | renderIcon | customize step icon(optional) | (params: { starting: boolean; waiting: boolean; error: boolean; }) => React.ReactNode | - | --- ## SwipeAction Source: https://rn.mobile.ant.design/components/swipe-action.md # SwipeAction iOS-style swipeout buttons that appear from behind a component. ### Definition Call out operations from one side of screen with gesture. ### Rules 1. Only one row can be swiped at a time. 2. Can hide operations by clicking outside of buttons or swiping the list backforwards. ## Examples ```tsx import { List, SwipeAction } from '@ant-design/react-native' import React from 'react' import { View } from 'react-native' export default class BasicSwipeActionExample extends React.Component { asyncFunction = () => { return new Promise((resolve) => { setTimeout(() => { console.log('asd') resolve(123) }, 1500) }) } render() { const right = [ { text: 'More', onPress: async () => { await this.asyncFunction() }, backgroundColor: 'orange', color: 'white', }, { text: 'Delete', onPress: () => console.log('delete'), backgroundColor: 'red', color: 'white', }, ] const left = [ { text: 'Read', onPress: () => console.log('read'), backgroundColor: 'blue', color: 'white', }, { text: 'Reply', onPress: () => console.log('reply'), backgroundColor: 'green', color: 'white', }, ] return ( Simple example: left and right buttons console.log('open')} onSwipeableClose={() => console.log('close')}> Simple example: left and right buttons ) } } ``` ## API ### SwipeAction | Properties | Descrition | Type | Default | Version | |-----|-----|------|-------|------| | closeOnAction | Whether to return to the position automatically when the operation button is clicked | `boolean` | `true` | `5.2.1` | | closeOnTouchOutside | Whether to return to the position automatically when other areas is clicked | `boolean` | `false` | `5.2.1` | | left | List of operation buttons on the left | [SwipeoutButtonProps](/components/swipe-action#swipeoutbuttonprops)[] | `[]` | | | right | List of operation buttons on the right | [SwipeoutButtonProps](/components/swipe-action#swipeoutbuttonprops)[] | `[]` | | | styles | Semantic DOM style | [SwipeActionStyle](/components/swipe-action#swipeactionstyle-interface) | - | `5.2.1` | The rest of the props of `SwipeAction` are exactly the same as [react-native-gesture-handler/Swipeable](https://docs.swmansion.com/react-native-gesture-handler/docs/components/swipeable/), **eg: `onSwipeableOpen` , `onSwipeableClose` , `renderLeftActions` , `renderRightActions`** When you set `renderLeftActions` prop, it will override `left` prop;
when you set `renderRightActions` prop, it will override `right` prop. ### SwipeoutButtonProps | Properties | Descrition | Type | Default | Version | |-----|------|------|------|------| | backgroundColor | background color | `string` | - | | | color | font color | `string` | - | | | disabled | Whether disabled | `boolean` | - | | | onPress | Trigger when clicked | `() => void | Promise` | - | `5.2.1` support async | | style | Aaction button style, effective when `text` is `string` | `StyleProp` | - | | | text | Text | `string | ReactNode` | - | | | actionButtonProps | Rest props | [RectButtonProps](https://docs.swmansion.com/react-native-gesture-handler/docs/components/buttons/#rectbutton) | - | `5.2.1` | ### SwipeActionStyle interface ```typescript export interface SwipeActionStyle { actionButton: ViewStyle actionText: TextStyle } ``` ### Ref New in `5.2.1`. Ref to Swipeable[#Ref](https://docs.swmansion.com/react-native-gesture-handler/docs/components/swipeable/#methods) | Properties | Descrition | Type| |-----|------|------| | close | method that closes component | `() => void` | | openLeft | method that opens component on left side. | `() => void` | | openRight | method that opens component on right side. | `() => void` | | reset | method that resets the swiping states of this `Swipeable` component.
Unlike method `close`, this method does not trigger any animation. | `() => void` | --- ## Switch Source: https://rn.mobile.ant.design/components/switch.md # Switch Select between two status, e.g. Select On or Off. ### Rules - This is a **controlled component** that requires an `onChange` callback that updates the `checked` prop in order for the component to reflect user actions. ## Examples ```tsx import { Button, Icon, List, Switch, WhiteSpace, WingBlank } from '@ant-design/react-native' import React from 'react' import { ScrollView } from 'react-native' export default class SwitchExample extends React.Component { constructor(props: any) { super(props) this.state = { disabled: true, checked: false, } } toggle = () => { this.setState({ disabled: !this.state.disabled, }) } sleep1s = () => { return new Promise((resolve) => { setTimeout(resolve, 1000) }) } onChangeAsync = async (val: boolean) => { await this.sleep1s() this.setState({ checked: val, }) } render() { return ( }>最简单的用法 }> Switch 失效状态 } /> } /> } unCheckedChildren={} defaultChecked /> } /> }> 标识开关操作仍在执行中 } /> }> color="red" }> onChange 返回 Promise ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | checked | Whether is checked by default | Boolean | false | | defaultChecked | Whether to open initially | Boolean | false | | disabled | whether is disabled | Boolean | false | | loading | Loading status | Boolean | false | | onChange | The callback function when changing, when the Promise is returned, the loading status will be displayed automatically | `(val: boolean) => void \| Promise` | - | | color | Background color when the switch is turned on. | String | #4dd865 | | checkedChildren | Selected content | ReactNode | - | | unCheckedChildren | Non-selected content | ReactNode | - | | styles | Semantic DOM style | [SwitchStyle](#switchstyle-interface) | - | ### SwitchStyle interface ```typescript interface SwitchStyle { switch: ViewStyle switch_inner: ViewStyle switch_handle: ViewStyle switch_checked: ViewStyle switch_unchecked: ViewStyle switch_inner_checked: ViewStyle switch_inner_unchecked: ViewStyle switch_handle_checked: ViewStyle switch_handle_unchecked: ViewStyle switch_checked_disabled: ViewStyle switch_unchecked_disabled: ViewStyle switch_handle_disabled: ViewStyle } ``` --- ## TabBar Source: https://rn.mobile.ant.design/components/tab-bar.md # TabBar Located at the bottom of the APP, to facilitate users to quickly switch between different functional modules。 ### Rule - Used as a class of APP classification, the number of tab between 3-5 is better。 - Even if a Tab is not available, do not disable or remove the Tab。 - Use Badge make a hint,stay can also know that there is content update。 ## Examples ```tsx import { Icon, SearchBar, TabBar } from '@ant-design/react-native' import React from 'react' import { Text, View } from 'react-native' export default class BasicTabBarExample extends React.Component { constructor(props: any) { super(props) this.state = { selectedTab: 'redTab', } } renderContent(pageText: any) { return ( {pageText} ) } onChangeTab(tabName: any) { this.setState({ selectedTab: tabName, }) } render() { return ( } selected={this.state.selectedTab === 'blueTab'} onPress={() => this.onChangeTab('blueTab')}> {this.renderContent('Life Tab')} } title="Koubei" badge={2} selected={this.state.selectedTab === 'redTab'} onPress={() => this.onChangeTab('redTab')}> {this.renderContent('Koubei Tab')} } title="Friend" selected={this.state.selectedTab === 'greenTab'} onPress={() => this.onChangeTab('greenTab')}> {this.renderContent('Friend Tab')} } title="My" selected={this.state.selectedTab === 'yellowTab'} onPress={() => this.onChangeTab('yellowTab')}> {this.renderContent('My Tab')} ) } } ``` ## API ### TabBar Properties | Descrition | Type | Default -----------|------------|------|-------- | barTintColor | tabbar's background color | String | `white` | | tintColor | selected's font color | String | `#108ee9` | | unselectedTintColor | unselected's font color | String | '#888' | | hidden | whether it is hidden | Boolean | false | ### TabBar.Item Properties | Descrition | Type | Default -----------|------------|------|-------- | badge | badge number | Number \ String | 无 | | onPress | on press the bar, need change component by yourself. state & selecte={true} | Function | `(){}` | | selected | whether it is selected | Boolean | false | | icon | the default icon | `Image Source | React.ReactNode` | | | selectedIcon | the icon of selected | `Image Source | React.ReactNode` | | | title | title | String | | | key | unique identification | String | 无 | | iconStyle | icon style | String | { width: 28, height: 28 } | --- ## Tabs Source: https://rn.mobile.ant.design/components/tabs.md # Tabs A `Tabs` is used to allow users to switch between different views. ### Rule - Generally a `Tabs` should have 2-4 tab pane, the title of each tab pane should be concise,normally has 2-4 words.. - In the secondary page of iOS, it is not recommended to use left and right swipe to switch tab, which conflicts with back swipe gestrue in iOS. eg: tabs in details page. ## Examples ```tsx import React from 'react' import { ScrollView, Text, TouchableOpacity, View } from 'react-native' import Tabs from '..' const renderContent = (tab: any, index: any) => { const style = { paddingVertical: 40, justifyContent: 'center', alignItems: 'center', margin: 10, backgroundColor: '#ddd', } as any const content = [1, 2, 3, 4, 5, 6, 7, 8].map((i) => { return ( {tab.title} - {i} ) }) return ( {content} ) } export default class BasicTabsExample extends React.Component { render() { const tabs = [ { title: 'First Tab' }, { title: 'Second Tab' }, { title: 'Third Tab' }, ] const tabs2 = [ { title: '1st Tab' }, { title: '2nd Tab' }, { title: '3rd Tab' }, { title: '4th Tab' }, { title: '5th Tab' }, { title: '6th Tab' }, { title: '7th Tab' }, { title: '8th Tab' }, { title: '9th Tab' }, ] const style = { alignItems: 'center', justifyContent: 'center', height: 150, backgroundColor: '#fff', } as any return ( Content of First Tab Content of Second Tab Content of Third Tab Custom RenderTabBar ( {tabProps.tabs.map((tab, i) => ( // change the style to fit your needs { const { goToTab, onTabClick } = tabProps // tslint:disable-next-line:no-unused-expression onTabClick && onTabClick(tabs[i], i) // tslint:disable-next-line:no-unused-expression goToTab && goToTab(i) }}> {tab.title} ))} )}> Content of First Tab Content of Second Tab Content of Third Tab {tabs2.map((tab, index) => renderContent(tab, index))} ) } } export const title = 'Tabs' export const description = 'Tabs example' ``` ## API ### Tabs Properties | Descrition | Type | Default | Required -----------|------------|------|--------|-------- tabs | tabs data | Models.TabData[] | | true tabBarPosition | TabBar's position | 'top' \| 'bottom' | top | false renderTabBar | replace the TabBar | ((props: TabBarPropsType) => React.ReactNode) \| false | | false initialPage | the tab when inital, index or key | number \| string | | false page | current tab, index or key | number \| string | | false swipeable | Whether to switch tabs with swipe gestrue in the content | boolean | true | false useOnPan | use hand scroll | boolean | true | false prerenderingSiblingsNumber | pre-render nearby # sibling, Infinity: render all the siblings, 0: render current page. | number | 1 | false animated | Whether to change tabs with animation | boolean | true | false onChange | Callback when tab is switched | (tab: Models.TabData, index: number) => void | | false onTabClick | on tab click | (tab: Models.TabData, index: number) => void | | false destroyInactiveTab | destroy inactive tab | boolean | false | false distanceToChangeTab | distance to change tab, width ratio | number | 0.3 | false usePaged | use paged | boolean | true | false tabBarUnderlineStyle | style of the default tab bar's underline | React.CSSProperties \| any | | false tabBarBackgroundColor | color of the default tab bar's background | string | | false tabBarActiveTextColor | color of the default tab bar's text when active | string | | false tabBarInactiveTextColor | color of the default tab bar's text when inactive | string | | false tabBarTextStyle | tional styles to the tab bar's text | React.CSSProperties \| any | | false renderTab | render for replace the tab of tabbar | (tab: Models.TabData) => React.ReactNode | | false renderUnderline | renderUnderline | (style: any) => React.ReactNode | | false ### Tabs.DefaultTabBar Properties | Descrition | Type | Default | Required -----------|------------|------|--------|-------- goToTab | call this function to switch Tab | (index: number) => boolean | | true tabs | tabs data | Models.TabData[] | | true activeTab | current tab | number | | true animated | Whether to change tabs with animation | boolean | | true renderTab | render for replace the tab of tabbar | (tab: Models.TabData) => React.ReactNode | | false page | the size for the tab of tabbar | number | 5 | false onTabClick | on tab click | (tab: Models.TabData, index: number) => void | | false --- ## Tag Source: https://rn.mobile.ant.design/components/tag.md # Tag Tag for categorizing or markuping, can be used to make classification or mark the attributes and dimensions of objects. ### Rules - The content should be displayed completely. ## Examples ```tsx import { Tag, WhiteSpace } from '@ant-design/react-native' import React from 'react' import { View } from 'react-native' function onChange(selected: any) { console.log(`tag selected: ${selected}`) } export default class BasicTagExample extends React.Component { render() { return ( Basic Selected Disabled Callback { console.log('onClose') }} afterClose={() => { console.log('afterClose') }}> Closable Small and Readonly { console.log('onLongPress') }}> LongPress ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | small | Whether to show a smaller size | Boolean | `false` | | disabled | Whether is disabled | Boolean | `false` | | closable | Whether can be closed(invalid in `small` or `disabled` mode) | Boolean | `false` | | selected | Whether is selected by default | Boolean | `false` | | onChange | The callback function that is triggered when the selected state changes. | (selected: bool): void | - | | onClose | The callback function that is triggered when the tag is closed. | (): void | - | | afterClose | The callback function that is triggered after close. | (): void | - | | onLongPress | The callback function that is triggered when the tag is long pressed. | (): void | - | --- ## TextareaItem Source: https://rn.mobile.ant.design/components/textarea-item.md # TextareaItem > This package has been deprecated in `5.2.1`, recommend [components/Input.TextArea](/components/input#inputtextarea) A foundational component for inputting multi-line text into the app via a keyboard. ### Rule - Support text input via keyboard or clipboard. - The cursor can be moved horizontally. ## Examples ```tsx import { List, TextareaItem, Toast } from '@ant-design/react-native' import React from 'react' import { ScrollView } from 'react-native' export default class BasicTextAreaItemExample extends React.Component< any, any > { constructor(props: any) { super(props) this.state = { val: '默认带value', } } onChange = (val: any) => { // console.log(val); this.setState({ val }) } render() { return ( Toast.fail('Error message')} /> ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | value | the value to show for the textarea (see [react doc](https://facebook.github.io/react/docs/forms.html) for more information about controlled component) | String | | | defaultValue | provides an initial value that will change when the user starts typing. | String | - | | placeholder | the string that will be rendered before text input has been entered. | String | '' | | editable | whether is editable | bool | true | | disabled | whether is disabled | bool | false | | clear | whether to display the clear icon (it takes effect only if `editable` is `true` and `disabled` is `false`) | bool | false | | rows | sets the number of lines for a textarea | number | 1 | | count | it is used for word count and maxlength, the default is 0 which indicates that word count is turned off. | number | - | | onChange | callback that is called when the textarea's text changes. | (val: string): void | - | | error | whether to display error | bool | false | | onErrorClick | callback that is called when the error icon is clicked | (): void | | | autoHeight | auto adjust height (only use one of `autoHeight` and `rows` properties) | bool | false | | labelNumber | number of label text, valid value is 2 to 7 | number | `5` | | last | If it is the last item, the `borderBottom` will be removed, the default has `borderBottom` | bool | false | > More available react-native `TextareaItem` API can be found at [react-native TextInput](http://facebook.github.io/react-native/docs/textinput.html) --- ## Toast Source: https://rn.mobile.ant.design/components/toast.md # Toast A lightweight feedback or tips, used to display content that does not interrupt user operations. Suitable for page transitions, data interaction and other scenes. ### Rules - Toast with Icon, 4-6 words is recommended; Toast without Icon, the number of words should not exceed 14. ## Examples ```tsx import { Button, List, Provider, Switch, Toast } from '@ant-design/react-native' import React, { useEffect, useRef, useState } from 'react' import { ActivityIndicator, ScrollView, Text } from 'react-native' const ToastExample = () => { const handler = useRef() const [enableMask, setEnableMask] = useState(Toast.getConfig().mask) const [enableStack, setEnableStack] = useState(Toast.getConfig().stackable) return ( { Toast.config({ mask }) setEnableMask(Toast.getConfig().mask) }} /> }> Enable mask 是否显示透明蒙层,防止触摸穿透 { Toast.config({ stackable }) setEnableStack(Toast.getConfig().stackable) }} /> }> Enable stackable 是否允许叠加显示 ) } export default ToastExample const CountDownText = () => { const [count, setCount] = useState(5) const interval = useRef() useEffect(() => { interval.current = setInterval(() => { setCount((x) => { if (x > 1) { return x - 1 } else { return x } }) }, 1000) return () => { interval.current && clearInterval(interval.current) } }, []) return 还剩 {count} 秒 } ``` ## API `Toast` only supports Imperative calls. The argument type is `string | ToastProps`. - `Toast.show(props)` - New in `5.2.1` - `Toast.success(props)` - `Toast.fail(props)` - `Toast.info(props)` - `Toast.loading(props)` - `Toast.offline(props)` `Toast.show(string)`'s default config is `{duration:1.5, mask: false}`. Another method is to specify a shortcut to the `icon`. ToastProps has these fields: | Properties | Descrition | Type | Required | Default | Version | | ---------- | ---------- | -----| -----------| --------|---------| | content | Toast content | `String | React.ReactNode` | Yes | - | | | duration | Delay time to close, which units is second | number | No | 3 | | | icon | Toast icon | `'success' | 'fail' | 'offline' | 'loading' | React.ReactNode` | No | - | `5.2.1` | | mask | Whether to show a transparent mask, which will prevent touch event of the whole page | Boolean | No | true | | | onClose | A callback function Triggered when the Toast is closed | Function | No | - | | | position | Vertical display position | `'top' | 'bottom' | 'center'` | No | `'center'` | `5.2.1` | | stackable | Whether to allow toast overlay | Boolean | No | true | | | styles | Semantic DOM style | [ToastStyle](#toaststyle-interface) | No | - | `5.2.1` | > **Notice:** OnClose is invalid and Toast does not hide, If set duration = 0, toast will not auto hide, you have to manually do it. ```js import { Toast } from '@ant-design/react-native'; const key = Toast.loading('message'); Toast.remove(key); ``` ### Toast.removeAll Turn off `Toast` in all displays. ```ts Toast.removeAll() ``` ### Toast.config Methods for global configuration. Support `duration`、`mask`、`onClose`、`position`、`stackable` and `style`. The configuration method is as follows: ```ts Toast.config({ duration: 1, position: 'top' }) // get current config Toast.getConfig() ``` ### Toast.useToast() New in `5.3.0`. antd-mobile-rn will inserted into the root node of `` through `Portal.add` when call toast methods. Whose context is different with origin code located context.
When you need context info (like **Modal** context), you can use `toast.useToast` to get `toastApi` instance and `contextHolder` node. And put it in your children: ```jsx import { Modal } from 'react-native' import { Toast } from '@ant-design/react-native' const [toastApi, contextHolder] = Toast.useToast(); const showLoading = () => { toastApi.loading( // ... ); } return ( {contextHolder} ... ); ``` ### InputStyle interface ```typescript interface ToastStyle { container: ViewStyle innerContainer: ViewStyle innerWrap: ViewStyle iconToast: ViewStyle textToast: ViewStyle content: TextStyle image: TextStyle centering: ViewStyle } ``` --- ## Tooltip Source: https://rn.mobile.ant.design/components/tooltip.md # Tooltip After clicking on a control or an area, a Tooltip menu appears for doing more. If set mask prop, it is recommended to exit by clicking on any of the mask layers. ## Examples ```tsx import { Button, Icon, List, Provider, Toast, Tooltip, } from '@ant-design/react-native' import React, { useEffect, useState } from 'react' import { ScrollView, Text, View } from 'react-native' import { Action, TooltipProps } from '../PropsType' const actions: Action[] = [ { key: 'scan', icon: , text: '扫一扫' }, { key: 'payment', icon: , text: '付钱/收钱' }, { key: 'bus', icon: , text: '乘车码' }, { key: 'assistant', icon: , text: '智能助理' }, ] export default function TooltipExample() { const [placement, setPlacement] = useState('top-start') useEffect(() => { let current = 0 const timer = setInterval(() => { if (current >= directionList.length - 1) { current = 0 } else { current += 1 } setPlacement(directionList[current]) }, 2000) return () => { clearInterval(timer) } }, []) return ( Popover Content
} styles={{ arrow: { borderTopColor: 'yellow' } }} placement={placement}> Toast.show(`选择了 ${node.text}`)} trigger="onPress"> Toast.show(`选择了 ${node.text}`)} trigger="onPress"> Toast.show(`选择了 ${node.text}`)} placement="bottom-start" trigger="onPress">
) } const directionList = [ 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start', ] as const ``` ## API ### Tooltip | Name | Description | Type | Default | | --- | --- | --- | --- | | children | The element that triggered the Tooltip | `React.ReactElement` | - | | content | The content of the Tooltip | `React.ReactNode` | - | | defaultVisible | Whether to show or hide by default | `boolean` | `false` | | mode | Set bright color mode or black mode | `'light' | 'dark'` | `'light'` | | crossOffset | Set the offset of the pop-up window position; Top: Additional offset applied along the main axis between the element and its triggering element. Left: Additional offset applied along the horizontal axis between the element and its triggering element. | `{ top: number, left: number }` | `'{ top: StatusBar.currentHeight, left: 0 } '` | | onVisibleChange | Callback when the visible prop is changed | `(visible: boolean) => void` | - | | placement | The position of the Tooltip | `'top' | 'top-start' | 'top-end' | 'right' | 'right-start' | 'right-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end'` | `'top'` | | styles | Semantic DOM style | [TooltipStyle](#tooltipstyle-interface) | - | | trigger | Event to trigger | `'onPress'` | - | | visible | Whether to display pop-up content in controlled mode | `boolean` | - | ### Ref | Name | Description | Type | | ------- | -------------------------------- | ------------ | | hide | Hide the Tooltip | `() => void` | | show | Show the Tooltip | `() => void` | | visible | Whether the Tooltip is diplaying | `boolean` | ## Tooltip.scrollProps While `Tooltip` is inside a ``, please pread `Tooltip.scrollProps` to the ScrollView,
otherwise it will not follow the scroll ```jsx import { ScrollView } from 'react-native' import { Tooltip } from '@ant-design/react-native' ... ``` ## Tooltip.Menu ### Props Except for `content`, all other attributes are inherited from `Tooltip`, the unique attributes are as follows: | Name | Description | Type | Default | | --- | --- | --- | --- | | actions | Menu list, used when the pop-up content is a standard menu | `Action[]` | - | | maxCount | Maximum number of menu lists, if exceeded, hide for scrolling | `number` | - | | onAction | Callback of the selected menum, when the menu list is used | `(item: Action) => void` | - | ### Action | Name | Description | Type | Default | | --- | --- | --- | --- | | disabled | Whether disabled | `boolean` | `false` | | icon | The icon of the menu item | `ReactNode` | `null` | | key | The unique identifier of the menu, the default is `index` | `string | number` | `actions` array's `index` | | onPress | Triggered on click | `() => void` | - | | text | Menu list, used when the pop-up content is a standard menu | `ReactNode` | - | ### TooltipStyle interface ```typescript interface TooltipStyle extends ListItemStyle { tooltip: ViewStyle tooltipText: TextStyle arrow: ViewStyle // `borderTopColor` sets the arrow bg color } ``` ### Ref Same as Tooltip. ## FAQ ### Why can't some children components wrapped by Tooltip be opened onPress? First, Tooltip's children must be `React.ReactElement`, which is a JSX Element rather than a variable. ```jsx const element = {element} // ❌ DO NOT USE // ✅ YES ``` Secondly, the positioning of Tooltip is calculated based on `View.onLayout`, so the children component must support the [onLayout](https://reactnative.dev/docs/view#onlayout) event. ```jsx const CustomButton = (props: { onLayout: (event: LayoutChangeEvent) => void }) => ( ... ) press ``` --- ## View Source: https://rn.mobile.ant.design/components/view.md # View Safe View ### Rules - Support `string`/`number` ReactNode ## Examples ```tsx import { View } from '@ant-design/react-native' import React from 'react' export default class SafeViewExample extends React.Component { render() { return ( Hello World! ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | children | child component | `React.ReactNode` \| `React.ReactText` | - | | style | style | `StyleProp` \| `StyleProp` | - | > More available react-native `View` API can be found at [react-native View](http://facebook.github.io/react-native/docs/view.html) ## FAQ ### What difference between it and React Native's built-in components View and Text? React Native's View does not support `children` of type `string` / `number`. Misinformation will cause crash and no Code Line Numbers **This component can be used to evacuate errors once, giving priority to ensuring that the device does not crash.** Common mistakes: ```jsx const length = arr.length; {length && } // when length=0, actually render: 0 ``` Attention, only one layer of protection can be achieved, even `` children maked worng type: ```jsx import {View} from '@ant-design/react-native' {/* still crash */} 0 {/* still crash */} <>'' ``` --- ## WhiteSpace Source: https://rn.mobile.ant.design/components/white-space.md # WhiteSpace Layout controls ## Examples ```tsx import { WhiteSpace } from '@ant-design/react-native' import React from 'react' import { Text, View } from 'react-native' const PlaceHolder = (props: any) => ( Block ) export default class WhiteSpaceExample extends React.Component { render() { return ( ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | size | up and down margins, optional values:`xs`,`sm`,`md`,`lg`,`xl` | string | `md` | --- ## WingBlank Source: https://rn.mobile.ant.design/components/wing-blank.md # WingBlank Layout controls ## Examples ```tsx import { WhiteSpace, WingBlank } from '@ant-design/react-native' import React from 'react' import { Text, View } from 'react-native' const PlaceHolder = (props: any) => ( Block ) export default class WingBlankExample extends React.Component { render() { return ( ) } } ``` ## API Properties | Descrition | Type | Default -----------|------------|------|-------- | size | left and right blank space, optional values:`sm`,`md`,`lg` | string | `lg` | ---