From 99c2c2ff0b058dc64f66b23f8cb78af5bdfa36e8 Mon Sep 17 00:00:00 2001 From: afc163 Date: Fri, 19 Feb 2021 18:26:53 +0800 Subject: [PATCH] refactor: use optional chaining instead of if (#29368) * refactor: use optional chaining instead of if * revert some code --- components/affix/index.tsx | 4 +- components/anchor/Anchor.tsx | 4 +- components/anchor/AnchorLink.tsx | 4 +- components/button/button.tsx | 4 +- components/calendar/generateCalendar.tsx | 12 ++--- components/card/index.tsx | 4 +- components/cascader/index.tsx | 8 +--- components/checkbox/Group.tsx | 22 ++++----- components/form/Form.tsx | 4 +- .../form/demo/customized-form-controls.md | 4 +- components/input/Input.tsx | 47 +++++++++---------- components/layout/Sider.tsx | 8 +--- components/modal/Modal.tsx | 8 +--- components/page-header/index.tsx | 4 +- components/popconfirm/index.tsx | 14 ++---- components/radio/radio.tsx | 9 +--- components/table/Table.tsx | 23 ++++----- .../table/hooks/useFilter/FilterDropdown.tsx | 4 +- components/table/hooks/useSelection.tsx | 37 +++++---------- components/tag/CheckableTag.tsx | 8 +--- components/tag/index.tsx | 4 +- components/tooltip/index.tsx | 4 +- components/transfer/index.tsx | 28 ++++------- components/tree/DirectoryTree.tsx | 18 ++----- components/typography/Base.tsx | 10 +--- components/upload/UploadList/index.tsx | 4 +- 26 files changed, 98 insertions(+), 202 deletions(-) diff --git a/components/affix/index.tsx b/components/affix/index.tsx index 5722d0c620..943ba4a24a 100644 --- a/components/affix/index.tsx +++ b/components/affix/index.tsx @@ -215,9 +215,7 @@ class Affix extends React.Component { // Test if `updatePosition` called if (process.env.NODE_ENV === 'test') { const { onTestUpdatePosition } = this.props as any; - if (onTestUpdatePosition) { - onTestUpdatePosition(); - } + onTestUpdatePosition?.(); } }; diff --git a/components/anchor/Anchor.tsx b/components/anchor/Anchor.tsx index be21ddc881..e0aec98753 100644 --- a/components/anchor/Anchor.tsx +++ b/components/anchor/Anchor.tsx @@ -235,9 +235,7 @@ export default class Anchor extends React.Component { handleClick = (e: React.MouseEvent) => { const { scrollTo, onClick } = this.context; const { href, title } = this.props; - if (onClick) { - onClick(e, { title, href }); - } + onClick?.(e, { title, href }); scrollTo(href); }; diff --git a/components/button/button.tsx b/components/button/button.tsx index fdc7c4d56d..79c65fa414 100644 --- a/components/button/button.tsx +++ b/components/button/button.tsx @@ -197,9 +197,7 @@ const InternalButton: React.ForwardRefRenderFunction = (pr if (innerLoading) { return; } - if (onClick) { - (onClick as React.MouseEventHandler)(e); - } + (onClick as React.MouseEventHandler)?.(e); }; devWarning( diff --git a/components/calendar/generateCalendar.tsx b/components/calendar/generateCalendar.tsx index f2ac3ce814..f31fff7936 100644 --- a/components/calendar/generateCalendar.tsx +++ b/components/calendar/generateCalendar.tsx @@ -135,9 +135,7 @@ function generateCalendar(generateConfig: GenerateConfig) { // ====================== Events ====================== const triggerPanelChange = (date: DateType, newMode: CalendarMode) => { - if (onPanelChange) { - onPanelChange(date, newMode); - } + onPanelChange?.(date, newMode); }; const triggerChange = (date: DateType) => { @@ -152,9 +150,7 @@ function generateCalendar(generateConfig: GenerateConfig) { triggerPanelChange(date, mergedMode); } - if (onChange) { - onChange(date); - } + onChange?.(date); } }; @@ -166,9 +162,7 @@ function generateCalendar(generateConfig: GenerateConfig) { const onInternalSelect = (date: DateType) => { triggerChange(date); - if (onSelect) { - onSelect(date); - } + onSelect?.(date); }; // ====================== Locale ====================== diff --git a/components/card/index.tsx b/components/card/index.tsx index f4df15bfa0..fe87caa33b 100644 --- a/components/card/index.tsx +++ b/components/card/index.tsx @@ -67,9 +67,7 @@ const Card: CardInterface = props => { const size = React.useContext(SizeContext); const onTabChange = (key: string) => { - if (props.onTabChange) { - props.onTabChange(key); - } + props.onTabChange?.(key); }; const isContainGrid = () => { diff --git a/components/cascader/index.tsx b/components/cascader/index.tsx index 9f1067f452..517328f8bb 100644 --- a/components/cascader/index.tsx +++ b/components/cascader/index.tsx @@ -312,9 +312,7 @@ class Cascader extends React.Component { this.setState({ value }); } const { onChange } = this.props; - if (onChange) { - onChange(value, selectedOptions); - } + onChange?.(value, selectedOptions); }; getLabel() { @@ -359,9 +357,7 @@ class Cascader extends React.Component { } const { onPopupVisibleChange } = this.props; - if (onPopupVisibleChange) { - onPopupVisibleChange(popupVisible); - } + onPopupVisibleChange?.(popupVisible); }; handleInputBlur = () => { diff --git a/components/checkbox/Group.tsx b/components/checkbox/Group.tsx index 57f2cab9ea..51cb030c3a 100644 --- a/components/checkbox/Group.tsx +++ b/components/checkbox/Group.tsx @@ -94,18 +94,16 @@ const CheckboxGroup: React.FC = ({ if (!('value' in restProps)) { setValue(newValue); } - if (onChange) { - const opts = getOptions(); - onChange( - newValue - .filter(val => registeredValues.indexOf(val) !== -1) - .sort((a, b) => { - const indexA = opts.findIndex(opt => opt.value === a); - const indexB = opts.findIndex(opt => opt.value === b); - return indexA - indexB; - }), - ); - } + const opts = getOptions(); + onChange?.( + newValue + .filter(val => registeredValues.indexOf(val) !== -1) + .sort((a, b) => { + const indexA = opts.findIndex(opt => opt.value === a); + const indexB = opts.findIndex(opt => opt.value === b); + return indexA - indexB; + }), + ); }; const prefixCls = getPrefixCls('checkbox', customizePrefixCls); diff --git a/components/form/Form.tsx b/components/form/Form.tsx index 0b03a36964..6a813800f2 100644 --- a/components/form/Form.tsx +++ b/components/form/Form.tsx @@ -103,9 +103,7 @@ const InternalForm: React.ForwardRefRenderFunction = (props, React.useImperativeHandle(ref, () => wrapForm); const onInternalFinishFailed = (errorInfo: ValidateErrorEntity) => { - if (onFinishFailed) { - onFinishFailed(errorInfo); - } + onFinishFailed?.(errorInfo); let defaultScrollToFirstError: Options = { block: 'nearest' }; diff --git a/components/form/demo/customized-form-controls.md b/components/form/demo/customized-form-controls.md index 7a3a797d13..63b772b8ca 100644 --- a/components/form/demo/customized-form-controls.md +++ b/components/form/demo/customized-form-controls.md @@ -42,9 +42,7 @@ const PriceInput: React.FC = ({ value = {}, onChange }) => { const [currency, setCurrency] = useState('rmb'); const triggerChange = (changedValue: { number?: number; currency?: Currency }) => { - if (onChange) { - onChange({ number, currency, ...value, ...changedValue }); - } + onChange?.({ number, currency, ...value, ...changedValue }); }; const onNumberChange = (e: React.ChangeEvent) => { diff --git a/components/input/Input.tsx b/components/input/Input.tsx index 9e85e91a2a..88945bab96 100644 --- a/components/input/Input.tsx +++ b/components/input/Input.tsx @@ -68,23 +68,24 @@ export function resolveOnChange( | React.MouseEvent, onChange?: (event: React.ChangeEvent) => void, ) { - if (onChange) { - let event = e; - if (e.type === 'click') { - // click clear icon - event = Object.create(e); - event.target = target; - event.currentTarget = target; - const originalInputValue = target.value; - // change target ref value cause e.target.value should be '' when clear input - target.value = ''; - onChange(event as React.ChangeEvent); - // reset target ref value - target.value = originalInputValue; - return; - } - onChange(event as React.ChangeEvent); + if (!onChange) { + return; } + let event = e; + if (e.type === 'click') { + // click clear icon + event = Object.create(e); + event.target = target; + event.currentTarget = target; + const originalInputValue = target.value; + // change target ref value cause e.target.value should be '' when clear input + target.value = ''; + onChange(event as React.ChangeEvent); + // reset target ref value + target.value = originalInputValue; + return; + } + onChange(event as React.ChangeEvent); } export function getInputClassName( @@ -230,17 +231,13 @@ class Input extends React.Component { onFocus: React.FocusEventHandler = e => { const { onFocus } = this.props; this.setState({ focused: true }, this.clearPasswordValueAttribute); - if (onFocus) { - onFocus(e); - } + onFocus?.(e); }; onBlur: React.FocusEventHandler = e => { const { onBlur } = this.props; this.setState({ focused: false }, this.clearPasswordValueAttribute); - if (onBlur) { - onBlur(e); - } + onBlur?.(e); }; setValue(value: string, callback?: () => void) { @@ -320,12 +317,10 @@ class Input extends React.Component { handleKeyDown = (e: React.KeyboardEvent) => { const { onPressEnter, onKeyDown } = this.props; - if (e.keyCode === 13 && onPressEnter) { + if (onPressEnter && e.keyCode === 13) { onPressEnter(e); } - if (onKeyDown) { - onKeyDown(e); - } + onKeyDown?.(e); }; renderComponent = ({ getPrefixCls, direction, input }: ConfigConsumerProps) => { diff --git a/components/layout/Sider.tsx b/components/layout/Sider.tsx index c5509e0a46..83d878d9ae 100644 --- a/components/layout/Sider.tsx +++ b/components/layout/Sider.tsx @@ -98,18 +98,14 @@ const Sider = React.forwardRef( if (!('collapsed' in props)) { setCollapsed(value); } - if (onCollapse) { - onCollapse(value, type); - } + onCollapse?.(value, type); }; // ========================= Responsive ========================= const responsiveHandlerRef = useRef<(mql: MediaQueryListEvent | MediaQueryList) => void>(); responsiveHandlerRef.current = (mql: MediaQueryListEvent | MediaQueryList) => { setBelow(mql.matches); - if (onBreakpoint) { - onBreakpoint(mql.matches); - } + onBreakpoint?.(mql.matches); if (collapsed !== mql.matches) { handleSetCollapsed(mql.matches, 'responsive'); diff --git a/components/modal/Modal.tsx b/components/modal/Modal.tsx index 07fe9ef0e6..4492b6c793 100644 --- a/components/modal/Modal.tsx +++ b/components/modal/Modal.tsx @@ -142,16 +142,12 @@ const Modal: ModalInterface = props => { const handleCancel = (e: React.MouseEvent) => { const { onCancel } = props; - if (onCancel) { - onCancel(e); - } + onCancel?.(e); }; const handleOk = (e: React.MouseEvent) => { const { onOk } = props; - if (onOk) { - onOk(e); - } + onOk?.(e); }; const renderFooter = (locale: ModalLocale) => { diff --git a/components/page-header/index.tsx b/components/page-header/index.tsx index f83600fd0e..f07ffa208c 100644 --- a/components/page-header/index.tsx +++ b/components/page-header/index.tsx @@ -41,9 +41,7 @@ const renderBack = (
) => { - if (onBack) { - onBack(e); - } + onBack?.(e); }} className={`${prefixCls}-back-button`} aria-label={back} diff --git a/components/popconfirm/index.tsx b/components/popconfirm/index.tsx index 4bcf87ab20..97498d9549 100644 --- a/components/popconfirm/index.tsx +++ b/components/popconfirm/index.tsx @@ -61,25 +61,17 @@ const Popconfirm = React.forwardRef((props, ref) => { setVisible(value); } - if (props.onVisibleChange) { - props.onVisibleChange(value, e); - } + props.onVisibleChange?.(value, e); }; const onConfirm = (e: React.MouseEvent) => { settingVisible(false, e); - - if (props.onConfirm) { - props.onConfirm.call(this, e); - } + props.onConfirm?.call(this, e); }; const onCancel = (e: React.MouseEvent) => { settingVisible(false, e); - - if (props.onCancel) { - props.onCancel.call(this, e); - } + props.onCancel?.call(this, e); }; const onKeyDown = (e: React.KeyboardEvent) => { diff --git a/components/radio/radio.tsx b/components/radio/radio.tsx index 72649cad75..da18857b1e 100644 --- a/components/radio/radio.tsx +++ b/components/radio/radio.tsx @@ -18,13 +18,8 @@ const InternalRadio: React.ForwardRefRenderFunction = ( }, []); const onChange = (e: RadioChangeEvent) => { - if (props.onChange) { - props.onChange(e); - } - - if (context?.onChange) { - context.onChange(e); - } + props.onChange?.(e); + context?.onChange?.(e); }; const { prefixCls: customizePrefixCls, className, children, style, ...restProps } = props; diff --git a/components/table/Table.tsx b/components/table/Table.tsx index ede8df8df9..3ad6d08572 100644 --- a/components/table/Table.tsx +++ b/components/table/Table.tsx @@ -226,22 +226,19 @@ function Table(props: TableProps) { }); } - if (onChange) { - onChange(changeInfo.pagination!, changeInfo.filters!, changeInfo.sorter!, { - currentDataSource: getFilterData( - getSortData(rawData, changeInfo.sorterStates!, childrenColumnName), - changeInfo.filterStates!, - ), - action, - }); - } + onChange?.(changeInfo.pagination!, changeInfo.filters!, changeInfo.sorter!, { + currentDataSource: getFilterData( + getSortData(rawData, changeInfo.sorterStates!, childrenColumnName), + changeInfo.filterStates!, + ), + action, + }); }; /** - * Controlled state in `columns` is not a good idea that makes too many code (1000+ line?) to - * read state out and then put it back to title render. Move these code into `hooks` but still - * too complex. We should provides Table props like `sorter` & `filter` to handle control in next - * big version. + * Controlled state in `columns` is not a good idea that makes too many code (1000+ line?) to read + * state out and then put it back to title render. Move these code into `hooks` but still too + * complex. We should provides Table props like `sorter` & `filter` to handle control in next big version. */ // ============================ Sorter ============================= diff --git a/components/table/hooks/useFilter/FilterDropdown.tsx b/components/table/hooks/useFilter/FilterDropdown.tsx index 30f9e7bf7f..5a0358c144 100644 --- a/components/table/hooks/useFilter/FilterDropdown.tsx +++ b/components/table/hooks/useFilter/FilterDropdown.tsx @@ -127,9 +127,7 @@ function FilterDropdown(props: FilterDropdownProps) { ); const triggerVisible = (newVisible: boolean) => { setVisible(newVisible); - if (onFilterDropdownVisibleChange) { - onFilterDropdownVisibleChange(newVisible); - } + onFilterDropdownVisibleChange?.(newVisible); }; const mergedVisible = diff --git a/components/table/hooks/useSelection.tsx b/components/table/hooks/useSelection.tsx index 38a7000ddd..5749283fef 100644 --- a/components/table/hooks/useSelection.tsx +++ b/components/table/hooks/useSelection.tsx @@ -231,9 +231,7 @@ export default function useSelection( setMergedSelectedKeys(availableKeys); - if (onSelectionChange) { - onSelectionChange(availableKeys, records); - } + onSelectionChange?.(availableKeys, records); }, [setMergedSelectedKeys, getRecordByKey, onSelectionChange, preserveSelectedRowKeys], ); @@ -305,10 +303,7 @@ export default function useSelection( key: 'none', text: tableLocale.selectNone, onSelect() { - if (onSelectNone) { - onSelectNone(); - } - + onSelectNone?.(); setSelectedKeys([]); }, }; @@ -353,13 +348,11 @@ export default function useSelection( const keys = Array.from(keySet); - if (onSelectAll) { - onSelectAll( - !checkedCurrentAll, - keys.map(k => getRecordByKey(k)), - changeKeys.map(k => getRecordByKey(k)), - ); - } + onSelectAll?.( + !checkedCurrentAll, + keys.map(k => getRecordByKey(k)), + changeKeys.map(k => getRecordByKey(k)), + ); setSelectedKeys(keys); }; @@ -378,9 +371,7 @@ export default function useSelection( { - if (onSelectionClick) { - onSelectionClick(recordKeys); - } + onSelectionClick?.(recordKeys); }} > {text} @@ -519,13 +510,11 @@ export default function useSelection( } const keys = Array.from(keySet); - if (onSelectMultiple) { - onSelectMultiple( - !checked, - keys.map(recordKey => getRecordByKey(recordKey)), - changedKeys.map(recordKey => getRecordByKey(recordKey)), - ); - } + onSelectMultiple?.( + !checked, + keys.map(recordKey => getRecordByKey(recordKey)), + changedKeys.map(recordKey => getRecordByKey(recordKey)), + ); setSelectedKeys(keys); } else { diff --git a/components/tag/CheckableTag.tsx b/components/tag/CheckableTag.tsx index 3239618714..d68c98d260 100644 --- a/components/tag/CheckableTag.tsx +++ b/components/tag/CheckableTag.tsx @@ -27,12 +27,8 @@ const CheckableTag: React.FC = ({ const { getPrefixCls } = React.useContext(ConfigContext); const handleClick = (e: React.MouseEvent) => { - if (onChange) { - onChange(!checked); - } - if (onClick) { - onClick(e); - } + onChange?.(!checked); + onClick?.(e); }; const prefixCls = getPrefixCls('tag', customizePrefixCls); diff --git a/components/tag/index.tsx b/components/tag/index.tsx index 583790b409..bc8db06d38 100644 --- a/components/tag/index.tsx +++ b/components/tag/index.tsx @@ -87,9 +87,7 @@ const InternalTag: React.ForwardRefRenderFunction = ( const handleCloseClick = (e: React.MouseEvent) => { e.stopPropagation(); - if (onClose) { - onClose(e); - } + onClose?.(e); if (e.defaultPrevented) { return; diff --git a/components/tooltip/index.tsx b/components/tooltip/index.tsx index ff8d36190b..0346b6f571 100644 --- a/components/tooltip/index.tsx +++ b/components/tooltip/index.tsx @@ -150,8 +150,8 @@ const Tooltip = React.forwardRef((props, ref) => { if (!('visible' in props)) { setVisible(isNoTitle() ? false : vis); } - if (props.onVisibleChange && !isNoTitle()) { - props.onVisibleChange(vis); + if (!isNoTitle()) { + props.onVisibleChange?.(vis); } }; diff --git a/components/transfer/index.tsx b/components/transfer/index.tsx index 162f684f06..3e6136b6ac 100644 --- a/components/transfer/index.tsx +++ b/components/transfer/index.tsx @@ -197,9 +197,7 @@ class Transfer extends React.Com this.setStateKeys(oppositeDirection, []); this.handleSelectChange(oppositeDirection, []); - if (onChange) { - onChange(newTargetKeys, direction, newMoveKeys); - } + onChange?.(newTargetKeys, direction, newMoveKeys); }; moveToLeft = () => this.moveTo('left'); @@ -232,9 +230,7 @@ class Transfer extends React.Com handleFilter = (direction: TransferDirection, e: React.ChangeEvent) => { const { onSearch } = this.props; const { value } = e.target; - if (onSearch) { - onSearch(direction, value); - } + onSearch?.(direction, value); }; handleLeftFilter = (e: React.ChangeEvent) => this.handleFilter('left', e); @@ -243,9 +239,7 @@ class Transfer extends React.Com handleClear = (direction: TransferDirection) => { const { onSearch } = this.props; - if (onSearch) { - onSearch(direction, ''); - } + onSearch?.(direction, ''); }; handleLeftClear = () => this.handleClear('left'); @@ -280,20 +274,16 @@ class Transfer extends React.Com this.setStateKeys('right', []); - if (onChange) { - onChange( - targetKeys.filter(key => !selectedKeys.includes(key)), - 'left', - [...selectedKeys], - ); - } + onChange?.( + targetKeys.filter(key => !selectedKeys.includes(key)), + 'left', + [...selectedKeys], + ); }; handleScroll = (direction: TransferDirection, e: React.SyntheticEvent) => { const { onScroll } = this.props; - if (onScroll) { - onScroll(direction, e); - } + onScroll?.(direction, e); }; handleLeftScroll = (e: React.SyntheticEvent) => this.handleScroll('left', e); diff --git a/components/tree/DirectoryTree.tsx b/components/tree/DirectoryTree.tsx index 5c9dd50a3d..3ec9b6ff46 100644 --- a/components/tree/DirectoryTree.tsx +++ b/components/tree/DirectoryTree.tsx @@ -112,11 +112,7 @@ const DirectoryTree: React.ForwardRefRenderFunction setExpandedKeys(keys); } // Call origin function - if (props.onExpand) { - return props.onExpand(keys, info); - } - - return undefined; + return props.onExpand?.(keys, info); }; const onClick = (event: React.MouseEvent, node: EventDataNode) => { @@ -127,9 +123,7 @@ const DirectoryTree: React.ForwardRefRenderFunction onDebounceExpand(event, node); } - if (props.onClick) { - props.onClick(event, node); - } + props.onClick?.(event, node); }; const onDoubleClick = (event: React.MouseEvent, node: EventDataNode) => { @@ -140,9 +134,7 @@ const DirectoryTree: React.ForwardRefRenderFunction onDebounceExpand(event, node); } - if (props.onDoubleClick) { - props.onDoubleClick(event, node); - } + props.onDoubleClick?.(event, node); }; const onSelect = ( @@ -202,9 +194,7 @@ const DirectoryTree: React.ForwardRefRenderFunction newEvent.selectedNodes = convertDirectoryKeysToNodes(treeData, newSelectedKeys); } - if (props.onSelect) { - props.onSelect(newSelectedKeys, newEvent); - } + props.onSelect?.(newSelectedKeys, newEvent); if (!('selectedKeys' in props)) { setSelectedKeys(newSelectedKeys); } diff --git a/components/typography/Base.tsx b/components/typography/Base.tsx index 79eff936be..0a81979779 100644 --- a/components/typography/Base.tsx +++ b/components/typography/Base.tsx @@ -189,10 +189,7 @@ class Base extends React.Component { onExpandClick: React.MouseEventHandler = e => { const { onExpand } = this.getEllipsis(); this.setState({ expanded: true }); - - if (onExpand) { - (onExpand as React.MouseEventHandler)(e); - } + (onExpand as React.MouseEventHandler)?.(e); }; // ================ Edit ================ @@ -202,10 +199,7 @@ class Base extends React.Component { onEditChange = (value: string) => { const { onChange } = this.getEditable(); - if (onChange) { - onChange(value); - } - + onChange?.(value); this.triggerEdit(false); }; diff --git a/components/upload/UploadList/index.tsx b/components/upload/UploadList/index.tsx index e6ae32e5b6..c623881fd0 100644 --- a/components/upload/UploadList/index.tsx +++ b/components/upload/UploadList/index.tsx @@ -97,9 +97,7 @@ const InternalUploadList: React.ForwardRefRenderFunction { - if (onRemove) { - onRemove(file); - } + onRemove?.(file); }; const internalIconRender = (file: UploadFile) => {