React Native’s LayoutAnimation is Awesome
If you are developing with ReactNative and have not tried LayoutAnimation yet, you are missing out. Coming to ReactNative as an iOS developer, I was worried about losing the convenience of CoreAnimation. UIView animations are so nice; set the desired vie
If you are developing with ReactNative and have not tried LayoutAnimation yet, you are missing out.
Coming to ReactNative as an iOS developer, I was worried about losing the convenience of CoreAnimation. UIView animations are so nice; set the desired view properties and go. ReactNative’s Animated API works similarly, but requires a state property for each desired animation. For complex views this gets messy fast.
Enter LayoutAnimation. Don’t let the slim documentation scare you. It’s amazing.
For n number of layout changes in your view, one line does it all. Set your state, allow your view to re-render, and LayoutAnimation handles all interpolation for you. For large and complex views, this is POWERFUL.
In this example, I have a complex view with three possible states. Heights, widths, and item counts are rendered based on the state `index`, determined by which button is selected.
The state changing code without any animation is below.
Now, lets spice it up by adding a fancy LayoutAnimation. Only one line is necessary.
This will apply the `spring`animation preset to any layout changes that occur during the next render cycle.
LayoutAnimation comes with three presets:
Or you can roll your own. A couple examples of custom LayoutAnimations are shown below. It also helps to study the source code to see what all is possible.
LayoutAnimation works by identifying views by their unique key, computing their expected position, and relying on the underlying native framework (CoreAnimation on iOS) to animate the change. Frame changes are animated as long as the view keeps the same key between state changes. Opacity and Scale are the only additional properties supported, but it is possible to add a few more such as backgroundColor and transformations.
Note: I haven’t dug through the Android source code, so it might differ slightly there.
TLDR: LayoutAnimation is definitely worth recognition as a huge upside to React Native. Try it out and you’ll see.
Bài Viết Liên Quan
Ứng dụng Nhà Trọ 360 giúp người dùng tìm kiếm nhà trọ hoặc thuê nhà một cách nhanh chóng và tiện lợi, hỗ trợ tìm kiém trên tất cả các tỉnh thành...
MobiSocial Team coding style :)
Mùa thu đã về cùng hương vị ngòn ngọt của hoa sữa, khiến mọi thứ dường như bình yên hơn. Đã tự dặn lòng thôi chẳng chờ đợi nữa nhưng khi những...
Cơn mưa bất chợt là những rung động, tình cảm của nhân vật. Xuyên suốt truyện ngắn là hình ảnh của cơn mưa từ mát mẻ thanh thản đến lạnh lẽo cô...