我有一个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?.offsetHeight
或myRef.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>
</>
);
};