Skip to content

Commit

Permalink
fix: 修复 radioGroup 手动清除 value 样式不响应问题 (#536)
Browse files Browse the repository at this point in the history
  • Loading branch information
honkinglin authored Mar 24, 2022
1 parent 3031ac8 commit c022130
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
17 changes: 16 additions & 1 deletion src/_util/useDefault.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect, useRef } from 'react';
import noop from './noop';

export interface ChangeHandler<T, P extends any[]> {
Expand All @@ -13,6 +13,21 @@ export default function useDefault<T, P extends any[]>(
// 无论是否受控,都要 useState,因为 Hooks 是无条件的
const [internalValue, setInternalValue] = useState(defaultValue);

// 响应手动赋值 undefined, 跳过初始化阶段
const isMounted = useRef(false);
useEffect(() => {
if (!isMounted.current) {
isMounted.current = true;
return;
}

setInternalValue(value);

return () => {
isMounted.current = false;
};
}, [value]);

// 受控模式
if (typeof value !== 'undefined') {
return [value, onChange || noop];
Expand Down
5 changes: 3 additions & 2 deletions src/radio/RadioGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,15 @@ const RadioGroup = (props: RadioGroupProps) => {
const calcBarStyle = () => {
if (!variant.includes('filled')) return;
const checkedRadio = groupRef.current.querySelector(checkedRadioCls);
if (!checkedRadio) return;
if (!checkedRadio) return setBarStyle({ width: 0 });

const { offsetWidth, offsetLeft } = checkedRadio;
setBarStyle({ width: `${offsetWidth}px`, left: `${offsetLeft}px` });
};

useEffect(() => {
calcBarStyle();
}, [groupRef.current]); // eslint-disable-line react-hooks/exhaustive-deps
}, [groupRef.current, internalValue]); // eslint-disable-line react-hooks/exhaustive-deps

useMutationObservable(groupRef.current, calcBarStyle);

Expand Down

0 comments on commit c022130

Please sign in to comment.