问题
React keys are not working.
If I swap the position of two react elements (item0 and item1) positioned with transform transform: translate(); a css transition is triggered, only if the elements were rendered in the same order.
If I change the order of the render (position swap still the same but now item0 renders after item1), the css transition is not triggered.
It looks like react is deleting the DOM element and recreating it, even if they have React keys set.
Here is a simple JSfiddle with the problem.
https://jsfiddle.net/santiagopuentep/vvpezbp9/2/
Here is a written explanation:
Two React elements (item0 and item1) positioned with transform: translate(); in css and with a css transition active for that transform.
The app renders a list of items using a layout.
The first layout is:
item0 at translate(0px,0px); and item1 at translate(0px,50px);.
The second layout with the same items but with positions flipped:
item0 at translate(0px,50px); and item1 at translate(0px,0px);.
Clicking on any of the two items changed the layout back and forth from the two, swapping their positions and thus triggering the css transition for the position change.
This works just fine, the transitions trigger correctly.
The problem happens if the second layout makes the item1 render after item0 (only change in render order, css translate positions still swapped), the transition for the second element is lost.
This looks like React is deleting the element instead of just reordering it, even if I have keys set.
Please help!
回答1:
Thank you very much! I confirm this issue, so workaround is:
lastOrder = []
render() {
let cards=this.props.cardList
// HERE I RESORT NEW LIST LIKE PREVIOUS IT
if (this.lastOrder.length) cards.sort((a, b) =>
(this.lastOrder.indexOf(a.id) - this.lastOrder.indexOf(b.id)))
// AND SAVE LAST ORDER
this.lastOrder = cards.map(card => card.id)
return <div className='board'>
{cards.map(card => <Card key={card.id} {...card} />)}
</div>
}
来源:https://stackoverflow.com/questions/43508944/react-loses-css-transition-if-element-ordering-changes