【React】List使用QueueAnim动画效果不生效——QueueAnim与函数组件兼容性问题
版本:
- “antd-mobile”: “^5.37.1”,
- “rc-queue-anim”: “^2.0.0”,
问题
在使用 QueueAnim 时,如果动画的子元素是 Ant Design Mobile 中的组件(如 List.Item),可能会遇到动画不生效的问题,并且会看到类似以下警告:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
原因
Ant Design Mobile 中的组件(如 List.Item)在新版v5中是函数组件,而 QueueAnim 使用 ref 来控制动画,但函数组件不能直接使用 ref,导致动画无法正常执行。
解决方法
-
使用
div包裹组件:
因为QueueAnim需要将key放在最外层元素上,而且div能正常支持ref,所以可以使用div包裹需要动画的组件(例如List.Item),并将key放在div上。 -
代码更新:
你只需要在div上设置key,并且确保QueueAnim的动画应用在div上,而不是直接应用在List.Item上。
代码示例
import React from 'react';
import { List } from 'antd-mobile';
import QueueAnim from 'rc-queue-anim';
function Chat({ msgs }) {
return (
<QueueAnim type="left" delay={100}>
{/* 只在 div 上设置 key,包裹 List.Item */}
{msgs.map((msg) => (
<div key={msg._id}>
<List.Item>
{msg.content}
</List.Item>
</div>
))}
</QueueAnim>
);
}
export default Chat;
总结
- 函数组件不支持
ref:新版的 Ant Design Mobile 组件(如List.Item)是函数组件,它们不能直接使用ref,导致QueueAnim动画效果无法生效。 - 使用
div包裹:通过将List.Item组件包裹在div元素内,并在div上添加key,可以避免上述问题,并使动画正常工作。
