当状态改变时,React-typing-animation 不会重新渲染

2024-02-10

我有以下组件

import React, { Component } from "react";
import Typing from "react-typing-animation";

export class InfoDisplayer extends Component {
  infos = ["this is a test", "this is another test"];

  updateDisplayedInfo() {
    if (this.state.currentIndex >= this.infos.length) {
      this.setState({
        currentInfo: this.infos[0],
        currentInfo: 0,
      });
    } else {
      this.setState(prevState => ({
        currentIndex: prevState.currentIndex + 1,
        currentInfo: this.infos[prevState.currentIndex + 1],
      }));
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      currentInfo: this.infos[0],
      currentIndex: 0,
    };

    this.updateDisplayedInfo = this.updateDisplayedInfo.bind(this);
  }

  render() {
    return (
      <Typing onFinishedTyping={this.updateDisplayedInfo}>
        {this.state.currentInfo}
      </Typing>
    );
  }
}

export default InfoDisplayer;

我在用着https://github.com/notadamking/react-typing-animation https://github.com/notadamking/react-typing-animation这是一个用于获取文本输入动画的组件。它有一个名为onFinishedTyping可以用来在打字完成后做一些事情。我使用它来更改组件状态以更新当前信息状态。

虽然那updateDisplayedInfo被称为和currentInfo更新后,该组件不会再次渲染。

为什么?我相信setState应该重新渲染组件。

Addition: online code
Edit epic-surf-b7pgy

谢谢https://stackoverflow.com/users/11872246/keikai https://stackoverflow.com/users/11872246/keikai编辑,您可以使用react dev工具查看第一次打字动画后状态已更改


一些注意点:

  • 添加循环
  • Add Typing.Reset

参考文档here https://github.com/notadamking/react-typing-animation#reset-component


import ReactDOM from "react-dom";

import "./styles.css";

import React, { Component } from "react";
import Typing from "react-typing-animation";

import "./styles.css";

const infos = ["this is a test", "this is another test"];

export class InfoDisplayer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentIndex: 0
    };
  }

  componentDidUpdate() {
    console.log(this.state.currentIndex);
  }

  updateDisplayedInfo = () => {
    this.setState({ currentIndex: this.state.currentIndex === 0 ? 1 : 0 });
  };

  render() {
    return (
      <Typing onFinishedTyping={this.updateDisplayedInfo} loop>
        {infos[this.state.currentIndex]}
        <Typing.Reset count={1} delay={500} />
      </Typing>
    );
  }
}

export default InfoDisplayer;

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <InfoDisplayer />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当状态改变时,React-typing-animation 不会重新渲染 的相关文章

随机推荐