【问题标题】:Refresh animate component in React在 React 中刷新动画组件
【发布时间】:2020-11-06 04:35:17
【问题描述】:

当应用程序开始时,我有一个从左到右移动宽度延迟的动画表,我希望在此示例中每次用户选择另一个国家时都有这种效果。但是此时此效果仅在从列表中选择第一个国家时起作用。我的目标是在每个选择上设置这个动画。我该如何做这个,使用 useEffect 或其他解决方案? codesanbox 对这个链接的影响 https://8xs9u.csb.app/

import React, {useState} from "react";
import "./styles.css";
import {data} from './data';

export default function App() {
  const [countrySelect, setCountrySelect] = useState('');

  let countries = ['Spain', 'Germany', 'England'];
  const optionCountry = countries.map((country, index) => (
    <option value={country} key={index}>
      {country}
    </option>
  ));

  const selectCountry = (e) => {
    setCountrySelect(e.target.value);
  };

  const showTable = data
  .filter(item => item.country === countrySelect)
  .map((item,index) => 
    <tr className='move' style={{animationDelay: `${index / 2}s` }}>
      <td>{item.city}</td>
      <td>{item.pop}</td>
      </tr>
    )
  return (
    <div className="App">
      
      <div className="select">
        Show country:
        <select onChange={selectCountry}>{optionCountry}</select>
      </div>
      <table className="table">
        <tr>
          <th>City</th>
          <th>Pop</th>
        </tr>
        {showTable}
      </table>
    
    </div>
  );
}


.App {
  font-family: sans-serif;
  text-align: center;
}
table {
  margin: auto;
}
tr.move {
  top: 0;
  transform: translateX(-100%);
  animation: animate 2s;
  animation-fill-mode: forwards;
}
@keyframes animate {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0px);
  }
}

【问题讨论】:

    标签: javascript reactjs css-animations


    【解决方案1】:

    我这样做是一种非常奇怪的方式 添加类 move2 ,它是该类的 move 和关键帧 animate2 的副本,并且状态显示在执行 selectCountry() 时更改真/假状态。 它正在工作,但我不确定这是一个好的解决方案

    添加代码:

    const [show, setShow] = useState(true);
    const selectCountry = (e) => {
        setCountrySelect(e.target.value);
        setShow(!show);
      };
    ...
    <tr
            className={show ? "move" : "move2"}
            style={{ animationDelay: `${index / 2}s` }}
      >
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2016-09-20
      • 2019-11-02
      • 2018-01-05
      • 2018-12-17
      相关资源
      最近更新 更多