使用ReactJS进行共享元素转换

tho*_*ght 15 javascript css jquery css3 reactjs

在Android中,共享元素转换允许两个页面中存在的两个完全相同的元素在转换页面时链接在一起,就像下面显示的gif中的专辑封面一样:

Android共享元素转换

我想知道是否有可能在类之间使用ReactJS实现相同类型的转换.如果是这样,任何例子?如果没有,用jQuery怎么样?

Kei*_*ith 6

您几乎可以完全使用 CSStransform属性来完成此转换。React JS 就是操作 DOM,但你不需要在这里做太多。

动画:

  1. 隐藏小面板的文本内容。
  2. 缩放图片和文本背景以填充全屏。
  3. 放入新的文本内容。

其中 1 和 3 用 React 很容易,所以你只需要过渡动画。

这是一个非常非常基本的示例,根本不使用 JS:

body {
  background-color: #ccc;
}

.card {
  width: 150px;
  padding: 0;
  margin: 0;
  background-color: #fff;
  position: absolute;
  top: 0: left: 0;
  z-index: 1;
  
  /* Transition properties mean changes to them are animated */
  transition-property: transform;
  transition-timing-function: ease-in-out;
  transition-duration: 500ms;
  transform-origin: top left;
}

.card>img {
  width: 150px;
  height: 150px;
  margin: 0;
  padding: 0;
}

.card>.content {
  width: 150px;
  height: 50px;
  background-color: #fff;
  margin: 0;
}


/* This is only for the purposes of this demo.
 * In production you'd have an underlying grid layout and JS to figure out the position */
.card:nth-of-type(2) {
  left: 175px;
}

.card:nth-of-type(3) {
  top: 230px;
}

.card:nth-of-type(4) {
  top: 230px;
  left: 175px;
}


/* On hover transform the card to full size and translate it to the top left
 * Note that translate comes before scale. */
.card:nth-of-type(1):hover {
  transform: scale(2.1667);
  z-index: 2;
}

.card:nth-of-type(2):hover {
  transform: translate(-175px, 0) scale(2.1667);
  z-index: 2;
}

.card:nth-of-type(3):hover {
  transform: translate(0, -230px) scale(2.1667);
  z-index: 2;
}

.card:nth-of-type(4):hover {
  transform: translate(-175px, -230px) scale(2.1667);
  z-index: 2;
}
Run Code Online (Sandbox Code Playgroud)
<div class="card">
  <img src="http://via.placeholder.com/325/F50057/ffffff">
  <div class="content"></div>
</div>

<div class="card">
  <img src="http://via.placeholder.com/325/F44336/ffffff">
  <div class="content"></div>
</div>

<div class="card">
  <img src="http://via.placeholder.com/325/1DE9B6/000000">
  <div class="content"></div>
</div>

<div class="card">
  <img src="http://via.placeholder.com/325/FFEB3B/000000">
  <div class="content"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

基本技巧是使用CSStransformtranslatescale-这些特性可以通过显卡进行处理,所以保持平稳动画甚至在移动。

请注意,CSS 相当笨重 - 我这样做只是为了表明它可以用纯 CSS 完成。在实践中,您将需要一些 JS 来设置偏移属性、连接点击事件等。

另一个技巧(我在这里没有做过)是向后缩放动画 - 从全尺寸控件开始和translate/scale它向下到它似乎开始的位置。当用户点击它时,删除transform- 保存浏览器在开始动画之前必须重新计算完整大小的对象的 DOM。