gpt4 book ai didi

javascript - 将 React 函数转换为 React 类

转载 作者:行者123 更新时间:2023-12-02 22:45:12 26 4
gpt4 key购买 nike

我正在尝试将 react 函数转换为 react 类

  const prevSplash = () => {
if (index === 1) {
setIndex(0);
} else {
setIndex(prev => prev - 1);
}
}

const [index, setIndex] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => {
if (index === 1) {
setIndex(0);
} else {
setIndex(prev => prev + 1);
}
}, 10000);
return () => clearInterval(timer);
},);

最佳答案

尝试在类的 this.state 中定义 useState 属性,并在 componentDidMount 中定义 useEffect 函数。

您的代码将类似于:

import React,{Component} from 'react';
class Demo extends Component{
constructor(props){
super(props);
this.state = {
index:0
}
}

prevSplash = () => {
if (this.state.index === 1) {
this.setState({...this.state,index:0});
} else {
this.setState((prev)=>({
index:prev.index-1
}));
}
}

componentDidMount(){
const timer = setInterval(() => {
if (this.state.index === 1) {
this.setState({...this.state,index:0});
} else {
this.setState((prev)=>({
index:prev.index+1
}));
}
}, 10000);

return () => clearInterval(timer);

};

render() {
return (
<h1>
//your code
</h1>
)
}
}
}

export default Demo;

关于javascript - 将 React 函数转换为 React 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58428871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com