没有未知目标尺寸的 Reactjs 幻灯片动画问题
Reactjs slide animation problem without unknown target dimensions
在我的 React 应用程序中,我正在制作某种动画以使其更美观。我想通过从上方滑动使 div 出现,然后向后滑动消失。
我在堆栈中使用 bootstrap 5.1.0
和 react-bootstrap 1.6.1
。
我想出了一个解决方案,将内容包装在 div 中,并根据需要在 window.innerHeight
和 0
之间切换其 maxHeight
。我还添加了一个自定义 css class
.transition-height{
transition: max-height 0.5s ease-in-out;
}
问题很明显,当我关闭 div 时,动画从一个非常高的 maxHeight 值开始,因此在关闭触发事件和您看到 [=34 的那一刻之间存在延迟=] 实际关闭。我使用 window.innerHeight
是因为我没有要使用的已知高度目标值,它取决于 div 内容的长度。
我把代码上传到 codesandbox,所以你可以看到它的行为。
如何避免这种情况?
在您的情况下,只需要使用 useRef 获取 div 的高度,什么时候 show = true 设置当前高度。 codesandbox exapmle
ApperDiv
const AppearDiv = (props) => {
let { show = false, className = "", style = {} } = props;
const ref = useRef(null);
const getPaperBoxHeight = ref.current?.scrollHeight || 0;
const filteredProps = Object.entries(props)
.filter(([k, _]) => !["className", "show", "style"].includes(k))
.reduce((p, [k, v]) => ({ ...p, [k]: v }), {});
style = show ? { height: getPaperBoxHeight } : { height: 0 };
return (
<div
ref={ref}
className={
"overflow-hidden transition-height" + (className && ` ${className}`)
}
style={style}
{...filteredProps}
/>
);
};
在我的 React 应用程序中,我正在制作某种动画以使其更美观。我想通过从上方滑动使 div 出现,然后向后滑动消失。
我在堆栈中使用 bootstrap 5.1.0
和 react-bootstrap 1.6.1
。
我想出了一个解决方案,将内容包装在 div 中,并根据需要在 window.innerHeight
和 0
之间切换其 maxHeight
。我还添加了一个自定义 css class
.transition-height{
transition: max-height 0.5s ease-in-out;
}
问题很明显,当我关闭 div 时,动画从一个非常高的 maxHeight 值开始,因此在关闭触发事件和您看到 [=34 的那一刻之间存在延迟=] 实际关闭。我使用 window.innerHeight
是因为我没有要使用的已知高度目标值,它取决于 div 内容的长度。
我把代码上传到 codesandbox,所以你可以看到它的行为。
如何避免这种情况?
在您的情况下,只需要使用 useRef 获取 div 的高度,什么时候 show = true 设置当前高度。 codesandbox exapmle
ApperDiv
const AppearDiv = (props) => {
let { show = false, className = "", style = {} } = props;
const ref = useRef(null);
const getPaperBoxHeight = ref.current?.scrollHeight || 0;
const filteredProps = Object.entries(props)
.filter(([k, _]) => !["className", "show", "style"].includes(k))
.reduce((p, [k, v]) => ({ ...p, [k]: v }), {});
style = show ? { height: getPaperBoxHeight } : { height: 0 };
return (
<div
ref={ref}
className={
"overflow-hidden transition-height" + (className && ` ${className}`)
}
style={style}
{...filteredProps}
/>
);
};