我在构造函数中绑定了this.handleChange = this.handleChange.bind(this);
,但是仍然无法读取未定义的属性。
如何解决这个问题?
import React, { Component } from "react";
import moment from "moment";
class TimerConfig extends Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
}
handChange(ev) {
const newBaseTime = this.props.baseTime;
if (ev.target.id === "hours")
newBaseTime
.subtract(newBaseTime.get("hour"), "hours")
.add(parseInt(ev.target.value, 10), "hours");
if (ev.target.id === "minutes")
newBaseTime
.subtract(newBaseTime.get("minutes"), "minutes")
.add(parseInt(ev.target.value, 10), "minutes");
if (ev.target.id === "seconds")
newBaseTime
.subtract(newBaseTime.get("seconds"), "seconds")
.add(parseInt(ev.target.value, 10), "seconds");
this.props.setBaseTime(newBaseTime);
}
render() {
return (
<div>
<label for="hours">Hour</label>
<input
id="hours"
type="number"
defaultValue={this.props.baseTime.get("hours")}
onChange={this.handleChange}
/>
<label for="minutes">min</label>
<input
id="minutes"
type="number"
defaultValue={this.props.baseTime.get("minutes")}
onChange={this.handleChange}
/>
<label for="seconds">sec</label>
<input
id="seconds"
type="number"
defaultValue={this.props.baseTime.get("seconds")}
onChange={this.handleChange}
/>
</div>
);
}
}
export default TimerConfig;
答案 0 :(得分:0)
您拼写了方法“ handChange”而不是“ handleChange”:)
答案 1 :(得分:-1)
要在bind
中使用constructor
时,需要将super
与props
一起使用
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
}
否则,您可以使用以下语法进行绑定:
handChange=(ev)=>{
//..
}