首页 > 解决方案 > 如何修复包含由“间隔”更改的状态的翻译(React)

问题描述

我有一个动画计时器的程序。我想制作像https://stripe.com/us/customers这样的徽标动画。但是我有一个无休止的页面加载,所以它不起作用。

我尝试在代码的不同部分使用一个过程,并尝试更改间隔以进行更好的优化(我认为我的 PC 无法使用 1 ms 间隔),但这对我没有帮助。

这一切都来自一个文件。状态:

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      submitError: false,
      width: 0,
      height: 0,
      timer: 0
    };

程序:

 TimeForLogos() {
   const time = setInterval(() => {
   const passedTime = this.state.timer + 0.1;

   if (passedTime === 20) {
     clearInterval(time);
   }
   this.setState({
     timer: passedTime,
   });
  }, 100);
 }

我尝试在渲染中使用它(我需要在站点打开时开始该过程)并尝试制作一个按钮(我认为它可以帮助我解决无限加载的问题)。所以现在渲染的部分代码:

<div className={s.logos}>
  <span onClick={this.TimeForLogos()}>go</span>
      {LogoData.map(logo => (
        <div
          className={s.logo}
          style={{
            right: `${logo.positionX}px`,
            top: `${logo.positionY}px`,
            width: logo.width * 1.1,
            padding: `${(logo.width - logo.height) / 2} 0`,
            transform: `translate(${this.state.timer * 10}px,0) scale(1)`,
          }}
        >
          <img
            src={logo.img}
            alt=""
            style={{
              width: logo.width,
              height: logo.height,
            }}
          />
        </div>
     ))}
</div>

所以,一个问题。我怎样才能更新我的代码,它可以工作?而且我需要使程序在站点打开时起作用(打开站点时必须播放动画)。我该怎么做?

标签: javascriptcssreactjsreact-reduxfrontend

解决方案


您可以创建一个单独的组件并在超时函数中处理每个组件的转换。

class Home extends Component {
  constructor(props) {
    super(props);
    this.logoData = [{
      width: 100,
      height: 100,
      text: "text1"
    }, 
    {
      width: 100,
      height: 100,
      text: "text2"
    }, 
    {   width: 100,
        height: 100,
        text: "text3"
    }];

  }


  render() {
    return (
       <div className="mainContainer">
       {this.logoData.map(item => <MovingDiv {...item}/>)}
       </div>
    );
  }
}

再创建一个反应组件说MovingDiv

class MovingDiv extends Component {

    constructor(props) {
        super(props);
        this.state = {
            translateX: 0,
            translateY: 0,
            scale: 0
        }
    }

    componentDidMount() {
        const intervalLimit = setInterval(() => {
            let { translateX, translateY} = this.state;
            // logic of setting translateX goes here
            if(--translateX < -300) { // -300 is just for example
                translateX = 0;
            }
            this.setState({
                translateX
            })
        }, 200)
    }
    /* will move the divs towards right every 200ms*/
    render() {
        return(<div style={{ width: this.props.width, height: this.props.height, transform: `translate(${this.state.translateX}px, 0px)`}}>{this.props.text}</div>);
    }
}

希望这可以帮助!


推荐阅读