reactjs - Unexpected behavior of React render props
问题描述
I've come up with the following code using React Transition Group:
const Transition = ({ elements, selectKey, render: Element, ...props }) => (
<TransitionGroup {...props}>
{elements.map((element) => (
<CSSTransition
key={selectKey(element)}
timeout={1000}
className="transition-slide"
>
<Element {...element} />
</CSSTransition>
))}
</TransitionGroup>
)
The key part here is that Transition
component receives the render
prop and renders it applying some transitions.
The way I expected for this to work:
<Transition render={(props) => <Toast {...props} />} />
But this code does not work as I expected: the transition of the next element interrupts the transition of the previous one.
However, this code works just fine:
const Element = (props) => <Toast {...props} />
// ...
<Transition render={Element} />
How can I fix this issue without putting the desired render-prop into a separate component?
Codesandbox: Example sandbox. The sandbox presents a non-working option with animation interruption. To get a working version, you need to uncomment lines 16 and 30 in the /Toasts/index.js
file
P.S. I can't just use
render={Toast}
because I need to do({id}) => <Toast dismiss={() => {deleteToast(id)}} />
. I omitted this detail in order to simplify the understanding of the problem.
解决方案
If you don't want to put the render function into another component, putting it into a useCallback() solved it for me.
const Toasts = () => {
const [toasts, addToast] = useToasts();
const Element = useCallback((props) => <Toast {...props} />, []);
return (
<div>
<button onClick={addToast}>Add toast</button>
<List>
<Transition
elements={toasts}
selectKey={({ id }) => id}
render={Element}
/>
</List>
</div>
);
}
(I don't quite understand the origin of the issue, but it has to do something with the function references.)
推荐阅读
- excel - 有没有办法在 VBA 监视窗口/本地查看范围对象的当前地址?
- linux - Yocto - 构建依赖项
- javascript - 拆分 URL 以使用 Javascript 设置 cookie
- tsql - SQL查询按月汇总分类帐数据,按客户分组
- spring-boot - Spring Boot 调用 https 获取 PDF
- asp.net - 如何在 Asp.net core 3.0 中将 url 或电子邮件或特殊字符设置为 cookie?
- python - Python pandas 计算子字符串的唯一字符串源的数量
- r - 如何将 1 行拆分为多行,其中列包含相同的值类型
- javascript - 如何以最高效的方式使用 Excel.js 更改每一行的样式?
- spring-boot - RabbitTemplate 错误:ApplicationContext 已关闭,ConnectionFactory 无法再创建连接