繁体   English   中英

我应该解决一个计时器的 React 练习并通过按钮重置它。我在重置我的计时器时遇到问题

[英]I should solve a React exercise of a timer and reset it by a button.I have problem with resetting my timer

我想创建一个带有重置按钮的计时器。 我必须用 React 编写的初始代码来做这个练习。 这是初始代码。

 import React, {Component} from 'react'; import './Timer.css'; export class Timer extends Component { render() { return <div className="container"> <div className="timer"> </div> <button>Reset Timer</button> </div>; } }

我尝试了两种解决方案,但每个解决方案都返回了不同的错误。 这是我的第一个解决方案。(图 1)图 1

错误是(图2)图2

我的第二个解决方案是...(图3)图3

 import React, {Component} from 'react'; import './Timer.css'; const initialState = { seconds: 0 } export class Timer extends Component { constructor(props) { super(props); this.state = initialState; } tick() { this.setState(state => ({ seconds: state.seconds + 1 })); } componentDidMount() { this.interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.interval); } resetTimer() { this.setState(initialState); } render() { return <div className="container"> <div className="timer"> {this.state.seconds} </div> <button onClick = {this.resetTimer}>Reset Timer</button> </div>; } }

它的错误是......(图4)图4

如何解决重置定时器的问题?

问题来自“this”范围。

要么你必须绑定你在类中使用的函数。

constructor( props ){
   super( props );
   this.resetTimer = this.resetTimer.bind(this);
}

第二种选择是在声明函数时使用箭头函数,以维护类上“this”的范围。

resetTimer = () => {
   this.setState(initialState);
}

而不是写作

`resetTimer() {
    this.setState(initialState);
    }`

使用箭头函数

const resetTimer=()=> { this.setState(initialState); }

这会起作用

第二种解决方案- 这是因为您没有绑定函数并在点击事件中调用它请参阅处理事件

所以在构造函数中添加这一行

this.resetTimer = this.resetTimer.bind();

我希望这能解决你的问题:)

您必须按照其他用户的建议将方法调用与事件绑定如果您不绑定该方法,它将始终在重新渲染时被调用

第一种方法

内部构造函数this.methodName = this.bind.methodName(this);

内部渲染()

render(){
return(
<button onClick={this.methodName}></button>
)
}

第二种方法

render(){
 return(
  <button onClick={()=>this.methodName()}></button>
 )
}

第三种方法

methodName = () => {
//scope
}

render(){
 return(
  <button onClick={this.methodName}></button>
 )
}

第三种类型不适用于旧版本的反应,您必须为此使用类实验插件,在这种情况下,您应该始终使用第一种方法

当您需要传递参数时,应始终使用第二种方法,否则不要使用该方法

另外请注意如果你只是写

<button onClick={this.methodName()}></button>

这意味着您正在调用该方法,但没有将其与事件绑定,即无论您是否单击该方法都将始终被调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM