我有以下组件
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
谢谢https://stackoverflow.com/users/11872246/keikai https://stackoverflow.com/users/11872246/keikai编辑,您可以使用react dev工具查看第一次打字动画后状态已更改
一些注意点:
参考文档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(使用前将#替换为@)