你好我最近开始学习反应,我有一些问题。我正在尝试制作简单的反应应用程序,我正在制作的其中一个组件是秒表。现在我遇到了问题,使用从父组件传递给我的秒表组件的道具。 这是我的应用程序组件:反应秒表
import React, {Component} from 'react';
import { Form,FormControl, Button} from 'react-bootstrap';
// Compoenents
import Clock from './Clock';
import Stopwatch from './Stopwatch';
// CSS
import './css/app.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
deadline: 'December 31, 2017',
newDeadline: '',
timer: 60,
newTimer: ''
}
}
changeDeadline() {
this.setState({deadline: this.state.newDeadline});
}
checkTimer() {
this.setState({timer: this.state.newTimer});
}
render() {
return (
<div className='app'>
<div className='appTitle'>
Countdown to {this.state.deadline}
</div>
<Clock
deadline={this.state.deadline} // This is how we send props to our child component
/>
<Form inline={true} >
<FormControl
className='deadlineInput'
type="text"
placeholder='Write date to check'
onChange={event => this.setState({newDeadline: event.target.value})}
onKeyPress={event => {
if(event.key === 'Enter') {
event.preventDefault();
this.changeDeadline();;
}
}}
/>
<Button
onClick={() => this.changeDeadline()}
>
Submit
</Button>
</Form>
<div className='stopwatchTitle'>
Use stopwatch to {this.state.timer} seconds
</div>
<Stopwatch
timer={this.state.timer} // This is how we send props to our child component
/>
<Form inline={true} >
<FormControl
className='timerInput'
type="text"
placeholder='Set your timer'
onChange={event => this.setState({newTimer: event.target.value})}
onKeyPress={event => {
if(event.key === 'Enter') {
event.preventDefault();
this.checkTimer();;
}
}}
/>
<Button
onClick={() => this.checkTimer()}
>
Start
</Button>
</Form>
</div>
)
}
}
export default App;
,这是我的秒表组件:
import React, {Component} from 'react';
// CSS
import './css/stopwatch.css';
class Stopwatch extends Component {
constructor(props) {
super(props);
this.state = {
stopWatch: 0,
}
this.decrementer = null;
}
// This function runs before component completely renders on the application (otherwise we might create infinite loop)
componentWillMount() {
this.startTimer(this.props.timer);
}
startTimer(timer) {
let stopWatch = timer;
console.log(stopWatch)
this.decrementer = setInterval(() =>
this.setState({
stopWatch: this.state.stopWatch - 1
})
, 1000);
}
render() {
return (
<div>
<div className='myStopwatch'> {this.state.stopWatch} seconds</div>
</div>
)
}
}
export default Stopwatch;
眼下应用程序总是从0开始计数,并进入负。我如何使用从父母传递给我的孩子组件的计时器道具?我希望我的秒表开始时间等于我的计时器道具。当它达到0时如何使倒计时停止?
你尝试过什么?赢得'这项工作? - 'if(this.state.stopWatch === 0){//不递减? }' – vijayst