我有以下组件
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,它是一个用于获取文本输入动画的组件。它有一个名为onFinishedTyping
的处理程序,它可以用于在输入完成后执行一些操作。我使用它来更改组件状态以更新当前的信息状态。
尽管调用了updateDisplayedInfo
并更新了currentInfo
,但组件不会再次呈现。
为什么?我认为setState
应该重新呈现组件.
加法:联机代码
由于使用了https://stackoverflow.com/users/11872246/keikai编辑,您可以使用react工具来查看状态在第一次输入动画之后发生了更改。
发布于 2019-12-21 09:52:58
一些注意事项:
Typing.Reset
参考这里文档
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);
https://stackoverflow.com/questions/59438304
复制相似问题