React js将类转换为函数

时间:2019-03-11 03:23:27

标签: reactjs function timer export

我目前有一个与类一起使用的计时器,但是我只需要使用函数,因此它可以与我正在运行的App.js文件一起使用,以显示所需的内容。这是我如何从应用程序调用文件的示例:

return (
<div>


  <h1>Example Timer</h1>
  <h2>Other files have been removed for example purposes</h2>

  <Timer onClick ={this.startTimer} />
</div>

)

这是我的Timer类,需要将其转换为函数,以便可以将其导出为:

export default function Timer(onClick)

这是计时器的整个类组件

import React from 'react';
import "./timer.css";


class Timer extends React.Component{

constructor(){
    super();
    this.state = { time: {}, seconds: 5, color: 'darkgrey'};
    this.timer = 0;
    this.startTimer = this.startTimer.bind(this);
    this.startCountDown = this.startCountDown.bind(this);

    }

convertToSeconds(sec){
let divisor_for_minutes = sec % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);

let divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);

var obj = {"m": minutes, "s": seconds};
return obj;
}

componentDidMount() {
    let timeLeftVar = this.convertToSeconds(this.state.seconds);
    this.setState({ time: timeLeftVar });
  }

startTimer(){
// If timer is not set, set the interval

if(this.timer === 0 && this.state.seconds > 0){
    // 1000 ms = 1 second
    this.timer = setInterval(this.startCountDown, 1000);

}
}

startCountDown() {
        let seconds = this.state.seconds - 1;
        if(seconds >= 0){
          if(seconds<=2){
            this.setState({color: 'red'})
          }
        this.setState({
            time: this.convertToSeconds(seconds),
            seconds: seconds
        });
      }
    else{
        this.setState({time: this.convertToSeconds(5), seconds: 5, color: 'darkgrey'});
        clearInterval(this.timer);
        this.timer = 0;
    }

}

render(){
    return(
  <div className="component-timer">

    <div class="startbtn">
        <button onClick={this.startTimer}>Start</button>
    </div>

      <div class="timer"><div style = {{color: this.state.color}}>
        m: {this.state.time.m} s: {this.state.time.s}
      </div>
  </div>

  </div>
    );
    }
}


export default Timer;

3 个答案:

答案 0 :(得分:0)

有了新版本的react,我们可以使用Hook useState,它看起来像这样

WebSettings webSettings = yourWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
yourWebView.loadUrl("yourWebUrl");

答案 1 :(得分:0)

这是使用react hooks从类组件到函数组件的逐行转换...(您需要的React版本高于16.8.x https://reactjs.org/docs/hooks-intro.html

import React, { useState, useEffect } from 'react';
import './timer.css';

export default function Timer() {
  const [seconds, setSeconds] = useState(5);
  const [time, setTime] = useState({});
  const [color, setColor] = useState('darkgrey');
  const [timer, setTimer] = useState(0);

  //only executes when component mounts by passing "[]".
  useEffect(() => {
    setTime(convertToSeconds(seconds));
  }, []);

  function convertToSeconds(sec) {
    let divisor_for_minutes = sec % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    let divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    var obj = { m: minutes, s: seconds };
    return obj;
  }

  function startTimer() {
    // If timer is not set, set the interval

    if (timer === 0 && seconds > 0) {
      // 1000 ms = 1 second
      setTimer(setInterval(startCountDown, 1000));
    }
  }

  function startCountDown() {
    let _seconds = seconds - 1;
    if (_seconds >= 0) {
      if (_seconds <= 2) {
        setColor('red');
      }
      setTime(convertToSeconds(_seconds));
      setSeconds(_seconds);
    } else {
      setTime(convertToSeconds(5));
      setSeconds(5);
      setColor('darkgrey');
      clearInterval(timer);
      setTimer(0);
    }
  }
  return (
    <div className="component-timer">
      <div className="startbtn">
        <button onClick={startTimer}>Start</button>
      </div>

      <div className="timer">
        <div style={{ color: color }}>
          m: {time.m} s: {time.s}
        </div>
      </div>
    </div>
  );
}

答案 2 :(得分:0)

您不需要功能即可工作,可以使用类组件,并使用它直接在index.js或要呈现的任何位置呈现

代码有点像这样

import React from 'react';
import ReactDOM from 'react-dom';
import Timer from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <div>
  <h1>Example Timer</h1>
  <h2>Other files have been removed for example purposes</h2>
  <Timer />
  </div>
  , document.getElementById('root'));
registerServiceWorker();