UNPKG

antd-mobile-taro-ui

Version:

以antd-mobile为设计标准,基于taro框架的微信小程序组件库

80 lines (72 loc) 2.35 kB
import { __awaiter } from "tslib"; import classNames from 'classnames'; import React, { useState } from 'react'; import { withNativeProps } from 'antd-mobile/es/utils/native-props'; import { usePropsValue } from 'antd-mobile/es/utils/use-props-value'; import { mergeProps } from 'antd-mobile/es/utils/with-default-props'; import { isPromise } from 'antd-mobile/es/utils/validate'; import { View } from '@tarojs/components'; import SpinLoading from '../spin-loading'; import { useConfig } from '../config-provider'; const classPrefix = `adm-switch`; const defaultProps = { defaultChecked: false }; export const Switch = p => { const props = mergeProps(defaultProps, p); const disabled = props.disabled || props.loading || false; const [changing, setChanging] = useState(false); const { locale } = useConfig(); const [checked, setChecked] = usePropsValue({ value: props.checked, defaultValue: props.defaultChecked, onChange: props.onChange }); const onClick = () => __awaiter(void 0, void 0, void 0, function* () { if (disabled || props.loading || changing) { return; } const nextChecked = !checked; if (props.beforeChange) { setChanging(true); try { yield props.beforeChange(nextChecked); setChanging(false); } catch (e) { setChanging(false); throw e; } } const result = setChecked(nextChecked); if (isPromise(result)) { setChanging(true); try { yield result; setChanging(false); } catch (e) { setChanging(false); throw e; } } }); return withNativeProps(props, React.createElement(View, { onClick: onClick, className: classNames(classPrefix, { [`${classPrefix}-checked`]: checked, [`${classPrefix}-disabled`]: disabled || changing }), "aria-label": locale.Switch.name, "aria-checked": checked, "aria-disabled": disabled }, React.createElement(View, { className: `${classPrefix}-checkbox` }, React.createElement(View, { className: `${classPrefix}-handle` }, (props.loading || changing) && React.createElement(SpinLoading, { className: `${classPrefix}-handle-loading` })), React.createElement(View, { className: `${classPrefix}-inner` }, checked ? props.checkedText : props.uncheckedText)))); };