refactor: use optional chaining instead of if (#29368)

* refactor: use optional chaining instead of if

* revert some code
This commit is contained in:
afc163 2021-02-19 18:26:53 +08:00 committed by GitHub
parent 2e0915e70f
commit 99c2c2ff0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 98 additions and 202 deletions

View File

@ -215,9 +215,7 @@ class Affix extends React.Component<AffixProps, AffixState> {
// Test if `updatePosition` called
if (process.env.NODE_ENV === 'test') {
const { onTestUpdatePosition } = this.props as any;
if (onTestUpdatePosition) {
onTestUpdatePosition();
}
onTestUpdatePosition?.();
}
};

View File

@ -235,9 +235,7 @@ export default class Anchor extends React.Component<AnchorProps, AnchorState, Co
this.setState({
activeLink: link,
});
if (onChange) {
onChange(link);
}
onChange?.(link);
}
};

View File

@ -41,9 +41,7 @@ class AnchorLink extends React.Component<AnchorLinkProps, any, AntAnchor> {
handleClick = (e: React.MouseEvent<HTMLElement>) => {
const { scrollTo, onClick } = this.context;
const { href, title } = this.props;
if (onClick) {
onClick(e, { title, href });
}
onClick?.(e, { title, href });
scrollTo(href);
};

View File

@ -197,9 +197,7 @@ const InternalButton: React.ForwardRefRenderFunction<unknown, ButtonProps> = (pr
if (innerLoading) {
return;
}
if (onClick) {
(onClick as React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>)(e);
}
(onClick as React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>)?.(e);
};
devWarning(

View File

@ -135,9 +135,7 @@ function generateCalendar<DateType>(generateConfig: GenerateConfig<DateType>) {
// ====================== 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<DateType>(generateConfig: GenerateConfig<DateType>) {
triggerPanelChange(date, mergedMode);
}
if (onChange) {
onChange(date);
}
onChange?.(date);
}
};
@ -166,9 +162,7 @@ function generateCalendar<DateType>(generateConfig: GenerateConfig<DateType>) {
const onInternalSelect = (date: DateType) => {
triggerChange(date);
if (onSelect) {
onSelect(date);
}
onSelect?.(date);
};
// ====================== Locale ======================

View File

@ -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 = () => {

View File

@ -312,9 +312,7 @@ class Cascader extends React.Component<CascaderProps, CascaderState> {
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<CascaderProps, CascaderState> {
}
const { onPopupVisibleChange } = this.props;
if (onPopupVisibleChange) {
onPopupVisibleChange(popupVisible);
}
onPopupVisibleChange?.(popupVisible);
};
handleInputBlur = () => {

View File

@ -94,18 +94,16 @@ const CheckboxGroup: React.FC<CheckboxGroupProps> = ({
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);

View File

@ -103,9 +103,7 @@ const InternalForm: React.ForwardRefRenderFunction<unknown, FormProps> = (props,
React.useImperativeHandle(ref, () => wrapForm);
const onInternalFinishFailed = (errorInfo: ValidateErrorEntity) => {
if (onFinishFailed) {
onFinishFailed(errorInfo);
}
onFinishFailed?.(errorInfo);
let defaultScrollToFirstError: Options = { block: 'nearest' };

View File

@ -42,9 +42,7 @@ const PriceInput: React.FC<PriceInputProps> = ({ value = {}, onChange }) => {
const [currency, setCurrency] = useState<Currency>('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<HTMLInputElement>) => {

View File

@ -68,23 +68,24 @@ export function resolveOnChange(
| React.MouseEvent<HTMLElement, MouseEvent>,
onChange?: (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => 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<HTMLInputElement | HTMLTextAreaElement>);
// reset target ref value
target.value = originalInputValue;
return;
}
onChange(event as React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>);
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<HTMLInputElement | HTMLTextAreaElement>);
// reset target ref value
target.value = originalInputValue;
return;
}
onChange(event as React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>);
}
export function getInputClassName(
@ -230,17 +231,13 @@ class Input extends React.Component<InputProps, InputState> {
onFocus: React.FocusEventHandler<HTMLInputElement> = e => {
const { onFocus } = this.props;
this.setState({ focused: true }, this.clearPasswordValueAttribute);
if (onFocus) {
onFocus(e);
}
onFocus?.(e);
};
onBlur: React.FocusEventHandler<HTMLInputElement> = 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<InputProps, InputState> {
handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
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) => {

View File

@ -98,18 +98,14 @@ const Sider = React.forwardRef<HTMLDivElement, SiderProps>(
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');

View File

@ -142,16 +142,12 @@ const Modal: ModalInterface = props => {
const handleCancel = (e: React.MouseEvent<HTMLButtonElement>) => {
const { onCancel } = props;
if (onCancel) {
onCancel(e);
}
onCancel?.(e);
};
const handleOk = (e: React.MouseEvent<HTMLButtonElement>) => {
const { onOk } = props;
if (onOk) {
onOk(e);
}
onOk?.(e);
};
const renderFooter = (locale: ModalLocale) => {

View File

@ -41,9 +41,7 @@ const renderBack = (
<div className={`${prefixCls}-back`}>
<TransButton
onClick={(e: React.MouseEvent<HTMLDivElement>) => {
if (onBack) {
onBack(e);
}
onBack?.(e);
}}
className={`${prefixCls}-back-button`}
aria-label={back}

View File

@ -61,25 +61,17 @@ const Popconfirm = React.forwardRef<unknown, PopconfirmProps>((props, ref) => {
setVisible(value);
}
if (props.onVisibleChange) {
props.onVisibleChange(value, e);
}
props.onVisibleChange?.(value, e);
};
const onConfirm = (e: React.MouseEvent<HTMLButtonElement>) => {
settingVisible(false, e);
if (props.onConfirm) {
props.onConfirm.call(this, e);
}
props.onConfirm?.call(this, e);
};
const onCancel = (e: React.MouseEvent<HTMLButtonElement>) => {
settingVisible(false, e);
if (props.onCancel) {
props.onCancel.call(this, e);
}
props.onCancel?.call(this, e);
};
const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {

View File

@ -18,13 +18,8 @@ const InternalRadio: React.ForwardRefRenderFunction<HTMLElement, RadioProps> = (
}, []);
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;

View File

@ -226,22 +226,19 @@ function Table<RecordType extends object = any>(props: TableProps<RecordType>) {
});
}
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 =============================

View File

@ -127,9 +127,7 @@ function FilterDropdown<RecordType>(props: FilterDropdownProps<RecordType>) {
);
const triggerVisible = (newVisible: boolean) => {
setVisible(newVisible);
if (onFilterDropdownVisibleChange) {
onFilterDropdownVisibleChange(newVisible);
}
onFilterDropdownVisibleChange?.(newVisible);
};
const mergedVisible =

View File

@ -231,9 +231,7 @@ export default function useSelection<RecordType>(
setMergedSelectedKeys(availableKeys);
if (onSelectionChange) {
onSelectionChange(availableKeys, records);
}
onSelectionChange?.(availableKeys, records);
},
[setMergedSelectedKeys, getRecordByKey, onSelectionChange, preserveSelectedRowKeys],
);
@ -305,10 +303,7 @@ export default function useSelection<RecordType>(
key: 'none',
text: tableLocale.selectNone,
onSelect() {
if (onSelectNone) {
onSelectNone();
}
onSelectNone?.();
setSelectedKeys([]);
},
};
@ -353,13 +348,11 @@ export default function useSelection<RecordType>(
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<RecordType>(
<Menu.Item
key={key || index}
onClick={() => {
if (onSelectionClick) {
onSelectionClick(recordKeys);
}
onSelectionClick?.(recordKeys);
}}
>
{text}
@ -519,13 +510,11 @@ export default function useSelection<RecordType>(
}
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 {

View File

@ -27,12 +27,8 @@ const CheckableTag: React.FC<CheckableTagProps> = ({
const { getPrefixCls } = React.useContext(ConfigContext);
const handleClick = (e: React.MouseEvent<HTMLSpanElement, MouseEvent>) => {
if (onChange) {
onChange(!checked);
}
if (onClick) {
onClick(e);
}
onChange?.(!checked);
onClick?.(e);
};
const prefixCls = getPrefixCls('tag', customizePrefixCls);

View File

@ -87,9 +87,7 @@ const InternalTag: React.ForwardRefRenderFunction<HTMLSpanElement, TagProps> = (
const handleCloseClick = (e: React.MouseEvent<HTMLElement>) => {
e.stopPropagation();
if (onClose) {
onClose(e);
}
onClose?.(e);
if (e.defaultPrevented) {
return;

View File

@ -150,8 +150,8 @@ const Tooltip = React.forwardRef<unknown, TooltipProps>((props, ref) => {
if (!('visible' in props)) {
setVisible(isNoTitle() ? false : vis);
}
if (props.onVisibleChange && !isNoTitle()) {
props.onVisibleChange(vis);
if (!isNoTitle()) {
props.onVisibleChange?.(vis);
}
};

View File

@ -197,9 +197,7 @@ class Transfer<RecordType extends TransferItem = TransferItem> 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<RecordType extends TransferItem = TransferItem> extends React.Com
handleFilter = (direction: TransferDirection, e: React.ChangeEvent<HTMLInputElement>) => {
const { onSearch } = this.props;
const { value } = e.target;
if (onSearch) {
onSearch(direction, value);
}
onSearch?.(direction, value);
};
handleLeftFilter = (e: React.ChangeEvent<HTMLInputElement>) => this.handleFilter('left', e);
@ -243,9 +239,7 @@ class Transfer<RecordType extends TransferItem = TransferItem> 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<RecordType extends TransferItem = TransferItem> 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<HTMLUListElement>) => {
const { onScroll } = this.props;
if (onScroll) {
onScroll(direction, e);
}
onScroll?.(direction, e);
};
handleLeftScroll = (e: React.SyntheticEvent<HTMLUListElement>) => this.handleScroll('left', e);

View File

@ -112,11 +112,7 @@ const DirectoryTree: React.ForwardRefRenderFunction<RcTree, DirectoryTreeProps>
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<HTMLElement>, node: EventDataNode) => {
@ -127,9 +123,7 @@ const DirectoryTree: React.ForwardRefRenderFunction<RcTree, DirectoryTreeProps>
onDebounceExpand(event, node);
}
if (props.onClick) {
props.onClick(event, node);
}
props.onClick?.(event, node);
};
const onDoubleClick = (event: React.MouseEvent<HTMLElement>, node: EventDataNode) => {
@ -140,9 +134,7 @@ const DirectoryTree: React.ForwardRefRenderFunction<RcTree, DirectoryTreeProps>
onDebounceExpand(event, node);
}
if (props.onDoubleClick) {
props.onDoubleClick(event, node);
}
props.onDoubleClick?.(event, node);
};
const onSelect = (
@ -202,9 +194,7 @@ const DirectoryTree: React.ForwardRefRenderFunction<RcTree, DirectoryTreeProps>
newEvent.selectedNodes = convertDirectoryKeysToNodes(treeData, newSelectedKeys);
}
if (props.onSelect) {
props.onSelect(newSelectedKeys, newEvent);
}
props.onSelect?.(newSelectedKeys, newEvent);
if (!('selectedKeys' in props)) {
setSelectedKeys(newSelectedKeys);
}

View File

@ -189,10 +189,7 @@ class Base extends React.Component<InternalBlockProps, BaseState> {
onExpandClick: React.MouseEventHandler<HTMLElement> = e => {
const { onExpand } = this.getEllipsis();
this.setState({ expanded: true });
if (onExpand) {
(onExpand as React.MouseEventHandler<HTMLElement>)(e);
}
(onExpand as React.MouseEventHandler<HTMLElement>)?.(e);
};
// ================ Edit ================
@ -202,10 +199,7 @@ class Base extends React.Component<InternalBlockProps, BaseState> {
onEditChange = (value: string) => {
const { onChange } = this.getEditable();
if (onChange) {
onChange(value);
}
onChange?.(value);
this.triggerEdit(false);
};

View File

@ -97,9 +97,7 @@ const InternalUploadList: React.ForwardRefRenderFunction<unknown, UploadListProp
};
const onInternalClose = (file: UploadFile) => {
if (onRemove) {
onRemove(file);
}
onRemove?.(file);
};
const internalIconRender = (file: UploadFile) => {