UNPKG

@fruits-chain/react-native-xiaoshu

Version:
72 lines (66 loc) 2.33 kB
import React, { useCallback, useState, memo } from 'react'; import { View, Text } from 'react-native'; import { useTheme, widthStyle } from '../theme'; import { usePersistFn, useUpdateEffect } from '../hooks'; import { noop, isDef, isValue } from '../helpers'; import { createStyles } from './style'; import CheckboxIcon from './icon'; function Checkbox(_ref) { let { labelTextStyle, iconStyle, defaultValue, value, onChange, activeValue = true, inactiveValue = false, label, labelDisabled = false, labelPosition = 'right', iconSize = 20, renderIcon, disabled, activeColor, style, children } = _ref; if (disabled) { labelDisabled = disabled; } const onChangePersistFn = usePersistFn(onChange || noop); const [localValue, setLocalValue] = useState(isValue(value) ? value : isValue(defaultValue) ? defaultValue : inactiveValue); const THEME_VAR = useTheme(); const STYLES = widthStyle(THEME_VAR, createStyles); // 同步状态 useUpdateEffect(() => { setLocalValue(value); }, [value]); const onChangeValue = useCallback(() => { setLocalValue(s => { const v = s === activeValue ? inactiveValue : activeValue; // 做一个延迟,避免父组件更新的时候子组件也在更新 setTimeout(() => { onChangePersistFn(v); }, 0); return v; }); }, [activeValue, inactiveValue, onChangePersistFn]); const labelJSX = isDef(label) ? /*#__PURE__*/React.createElement(Text, { style: [STYLES.label, { [labelPosition === 'left' ? 'marginRight' : 'marginLeft']: THEME_VAR.checkbox_label_margin }, disabled ? STYLES.label_disabled : null, labelTextStyle], onPress: labelDisabled ? undefined : onChangeValue }, label) : children; const iconProps = { style: iconStyle, active: localValue === activeValue, activeColor, disabled, size: iconSize, onPress: onChangeValue }; const iconJSX = renderIcon ? renderIcon(iconProps) : /*#__PURE__*/React.createElement(CheckboxIcon, iconProps); return /*#__PURE__*/React.createElement(View, { style: [STYLES.checkbox, style] }, labelPosition === 'left' ? labelJSX : null, iconJSX, labelPosition === 'right' ? labelJSX : null); } export default /*#__PURE__*/memo(Checkbox); //# sourceMappingURL=index.js.map