我想用allTimeInSeconds
的值来设置timeToCountdown
的状态。
然后我想将该数据作为道具发送到组件。
class Timer extends Component {
constructor(props){
super(props);
this.state = {
hours: "",
minutes: "",
seconds: "",
timeToCountdown: ""
};
this.grabHours = this.grabHours.bind(this);
this.grabMinutes = this.grabMinutes.bind(this);
this.grabSeconds = this.grabSeconds.bind(this);
this.changeAllTimeInputsToSeconds = this.changeAllTimeInputsToSeconds.bind(this);
}
changeAllTimeInputsToSeconds(){
var timerHours = Number((parseInt(this.hours.value, 10)*3600)) || 0
var timerMinutes = Number((parseInt(this.minutes.value, 10)*60)) || 0
var timerSeconds = Number(parseInt(this.seconds.value, 10)) || 0
var allTimeInSeconds = timerHours + timerMinutes + timerSeconds;
this.setState({timeToCountDownValue: this.allTimeInSeconds});
console.log(allTimeInSeconds);
return allTimeInSeconds;
}
错误在这里:
var allTimeInSeconds = timerHours + timerMinutes + timerSeconds;
this.setState({ timeToCountDownValue: this.allTimeInSeconds });
变量this.allTimeInSeconds
不会退出。我想这会起作用:
const allTimeInSeconds = timerHours + timerMinutes + timerSeconds;
this.setState({ timeToCountDownValue: allTimeInSeconds });
我想,如果我正确理解了这个问题,你可以这样做:
假设timeToCountDown
是要作为属性发送的值,则无需在函数changeAllTimeInputsToSeconds
中返回该值。正如您已经执行的操作一样,您可以使用setState()
函数来更新state
值。然后它会自动发送到您的组件。
MyComponent
必须替换为组件,则需要发送属性。
class Timer extends Component {
constructor(props){
super(props);
this.state = {
hours: "",
minutes: "",
seconds: "",
timeToCountdown: 0,
};
this.grabHours = this.grabHours.bind(this);
this.grabMinutes = this.grabMinutes.bind(this);
this.grabSeconds = this.grabSeconds.bind(this);
this.changeAllTimeInputsToSeconds();
}
changeAllTimeInputsToSeconds(){
var timerHours = Number((parseInt(this.hours.value, 10)*3600)) || 0
var timerMinutes = Number((parseInt(this.minutes.value, 10)*60)) || 0
var timerSeconds = Number(parseInt(this.seconds.value, 10)) || 0
var allTimeInSeconds = timerHours + timerMinutes + timerSeconds;
this.setState({timeToCountDown: allTimeInSeconds });
console.log(allTimeInSeconds);
}
render() {
return (
<MyComponent timeToCountdown={this.state.timeToCountdown} />
)
}
get hours, minute and seconds value from the state
var timerHours = Number((parseInt(this.hours.value, 10)*3600)) || 0
var timerMinutes = Number((parseInt(this.minutes.value, 10)*60)) || 0
var timerSeconds = Number(parseInt(this.seconds.value, 10)) || 0
use this.state.hours in place of this.hours similar for other values
对于当前代码,即使在当前组件中,TimeToCountdown 的值也将为零