我需要在react组件中为text2创建一个延迟



如标题所示。您可以看到,在我的代码中,我有文本和text2,它们形成了输入效果的文本。但它们是同时开始的。我想在text2上创建一个延迟,以便它在文本完成时开始。如有任何帮助,我将不胜感激,并提前感谢您。

class Home extends Component {
constructor(props) {
super(props);
this.state = {
text:"This is sample text",
text2:"This is sample text for text2",
count:0,
show:"",
show2:"",
}
this.update = this.update.bind(this);
}

componentDidMount() {
this.timerID = setInterval(
() => this.update(),
300
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

update(){
const counter = this.state.count;
const letter = this.state.text.charAt(counter);
const letter2 = this.state.text2.charAt(counter);
const textlength = this.state.text.length;
//let text += letter;
console.log("counter : " + counter + " / letter : " + letter);
console.log("counter : " + counter + " / letter2 : " + letter2);

if(counter <= textlength){
this.setState({
show: this.state.show + letter,
show2: this.state.show2 + letter2,
count: this.state.count + 1,
});
}else{
clearInterval(this.timerID);
}
};

给你

update() {
const counter = this.state.count;
const text1 = this.state.text;
const text2 = this.state.text2;
const letter = text1.charAt(counter);
// Note: It'll be empty string for negative index
const letter2 = text2.charAt(counter - text1.length);
const textlength = text1.length + text2.length;
if(counter < textlength) {
this.setState({
show: this.state.show + letter,
show2: this.state.show2 + letter2,
count: this.state.count + 1,
});
} else {
clearInterval(this.timerID);
}
}

最新更新