Javascript 将react函数转换为react类

Javascript 将react函数转换为react类,javascript,reactjs,function,class,classname,Javascript,Reactjs,Function,Class,Classname,我正在尝试将react函数转换为react类 const prevSplash = () => { if (index === 1) { setIndex(0); } else { setIndex(prev => prev - 1); } } const [index, setIndex] = React.useState(0); React.u

我正在尝试将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;
import React,{Component}来自'React';
类Demo扩展了组件{
建造师(道具){
超级(道具);
此.state={
索引:0
}
}
prevSplash=()=>{
if(this.state.index==1){
this.setState({…this.state,索引:0});
}否则{
此.setState((上一个)=>({
索引:prev.index-1
}));
}
}
componentDidMount(){
常量计时器=设置间隔(()=>{
if(this.state.index==1){
this.setState({…this.state,索引:0});
}否则{
此.setState((上一个)=>({
指数:上一指数+1
}));
}
}, 10000);
返回()=>clearInterval(计时器);
}; 
render(){
返回(
//你的代码
)
}
}
}
导出默认演示;

到目前为止,您尝试了什么?