Skip to content

Commit

Permalink
fix: 修复同时设置 activeKey 和 defaultActiveKey 导致的 bug
Browse files Browse the repository at this point in the history
  • Loading branch information
BestDingSheng committed Jun 29, 2021
1 parent a9a2586 commit d3fa7cb
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions packages/zarm/src/collapse/Collapse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,31 @@ interface CollapseStates {
multiple?: boolean;
}

const getActiveKey = (props: CollapseProps) => {
let isMount = true;

const initActiveKey = (props: CollapseProps) => {
const { multiple, activeKey, defaultActiveKey } = props;
let value;
if (typeof defaultActiveKey !== 'undefined') {
value = defaultActiveKey;
}
if (typeof activeKey !== 'undefined') {
value = activeKey || defaultActiveKey;
}

if (value) {
return multiple ? [].concat(value) : value;
}
return multiple ? [] : undefined;
};

const getActiveKey = (props: CollapseProps) => {
const { multiple, activeKey } = props;
let value;

if (typeof activeKey !== 'undefined') {
value = activeKey;
}
if (typeof defaultActiveKey !== 'undefined') {
value = defaultActiveKey;
}

if (value) {
return multiple ? [].concat(value) : value;
Expand All @@ -45,24 +60,25 @@ export default class Collapse extends Component<CollapseProps, CollapseStates> {
static Item: typeof CollapseItem;

state: CollapseStates = {
activeKey: getActiveKey(this.props),
activeKey: initActiveKey(this.props),
};

static getDerivedStateFromProps(nextProps: CollapseProps, state: CollapseStates) {
const newState: CollapseStates = {};
if ('activeKey' in nextProps && nextProps.activeKey !== state.prevActiveKey) {
newState.activeKey = getActiveKey(nextProps);
newState.prevActiveKey = nextProps.activeKey;
}
if ('animated' in nextProps) {
newState.animated = nextProps.animated;

if (!isMount) {
if ('activeKey' in nextProps && nextProps.activeKey !== state.activeKey) {
newState.activeKey = getActiveKey(nextProps);
}
}
if ('multiple' in nextProps) {
newState.multiple = nextProps.multiple;

if ('activeKey' in newState) {
return newState;
}
return 'activeKey' in newState || 'animated' in newState || 'multiple' in newState
? newState
: null;

isMount = false;

return null;
}

onItemChange = (onItemChange, key) => {
Expand Down Expand Up @@ -102,7 +118,8 @@ export default class Collapse extends Component<CollapseProps, CollapseStates> {
};

renderItems = () => {
const { activeKey, multiple, animated } = this.state;
const { activeKey } = this.state;
const { multiple, animated } = this.props;
return Children.map(this.props.children, (ele: ReactElement<CollapseItemProps>) => {
const { disabled, onChange } = ele.props;
const { key } = ele;
Expand Down

0 comments on commit d3fa7cb

Please sign in to comment.