为什么在使用useRef钩子的React组件中切换div的ref元素上,clientHeight或offsetHeigh



我有一个React组件,它显示和隐藏一些内容。

这是一个工作示例。

const Collapse = ({ children }: Props) => {
const [isOpen, setIsOpen] = useState(false);
const [height, setHeight] = useState<number | undefined>(0);
const toggledHeight = isOpen ? height : 0;
const myRef = useRef<HTMLDivElement>(null);
const toggle = () => setIsOpen(!isOpen);
useEffect(() => {
setHeight(myRef.current?.clientHeight);
}, [myRef]);
// useLayoutEffect(() => {
//   setHeight(myRef.current?.clientHeight);
// }, []);
return (
<React.Fragment>
<div
ref={myRef}
className={`content ${isOpen ? "isOpen" : ""}`}
style={{ height: `${toggledHeight}px` }}
>
{children}
{console.log(height)}
{console.log(myRef)}
</div>
<button type="button" onClick={toggle}>
<span>Toggle content</span>
</button>
</React.Fragment>
);
};
export default Collapse;

我想在显示和隐藏内容时创建一个cssheight转换。

为什么myRef.current?.offsetHeightmyRef.current?.clientHeight不可用,而总是0

在样式中,您正在传递动态高度。我认为它没有进入像素。所以你需要改变

style={{ height:${height+"px"}}}

看起来你从第一刻起就告诉它是0:(

无需查找确切的高度编号,只需将max-height动画化即可

我已经成功地为你制作了这样的动画代码:

const Collapse = ({ children }: Props) => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => {
setIsOpen(!isOpen);
};
return (
<>
<div
style={{
maxHeight: isOpen ? '1000px' : '0px',
transition: 'max-height 1s ease-in-out',
}}
>
{children}
</div>
<button type="button" onClick={toggle}>
<span>Toggle content</span>
</button>
</>
);
};

最新更新