//timeApp.js
import React, {Component} from 'react';
export default class MyTime extends Component{
constructor(props) {
super(props);
this.timer = null;
this.state = {
inputTime:'',//用来存储用户输入的内容
pressSeconds:0,
totalTime:0,
message:[{
in:'',
out:'',
}],
}
}
render(){
//遍历message数组 得到用户实际按压时间
let results = this.state.message.map((item) => {
return (
<div>
<p>您输入的时间为:{item.in} s</p>
<p>您实际的耗时为:{item.out} s</p>
</div>
)
});
return(
<div>
<p>请输入要测的时间:<input type={'text'} value={this.state.inputTime} onChange={this.inputFunc.bind(this)}/></p>
<h1
// 当鼠标按下时触发
onMouseDown = {() => {
//判断计时器是否存在
if(!this.timer === null){
return;
}
//pressSeconds和totalTime重新初始化
if(!(this.state.pressSeconds === 0)){
console.log('哈哈');
this.setState({
pressSeconds:0,
totalTime:0,
});
}
//当鼠标按下时开始计时
this.timer = setInterval(() => {
const seconds = this.state.pressSeconds;
this.setState({
pressSeconds:seconds + 1,
});
}, 1000);
}}
//当鼠标抬起时触发
onMouseUp = {() => {
//当鼠标抬起时计时暂停
clearTimeout(this.timer);
//将用户按下的时间保存在message数组中
this.setState({
message:[{
in:this.state.inputTime,
out:this.state.pressSeconds,
}],
});
}}>请按住{this.state.inputTime}秒</h1>
{results}
</div>
)
}
// 用户输入时的响应事件
inputFunc(event){
//接收用户输入的内容 保存到inputTime中
const inputMessage = event.target.value;
this.setState({
inputTime:inputMessage,
});
}
}
//app.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import MyTime from './myTimeThoughts';
import TimeApp from './timeApp';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>测测你的时间概念</h2>
</div>
<TimeApp/>
<MyTime />
</div>
);
}
}
export default App;