无法正确更改道具的父母。
我不知道该怎么做。
我将非常感谢您的帮助。
class ScheduleEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
times : document.getElementsByClassName('schedule')[0].value.split(' '),
items : [],
hour : [],
minute : []
};
}
updateItems(times) {
this.setState({times : times});
}
updateHM(time,val) {
debugger;
if(time == 'hour') {
this.setState(hour : val);
} else if(time == 'minute') {
debugger;
this.setState(minute : val);
}
}
render() {
this.state.items = [];
this.state.hour = [];
this.state.minute = [];
for (const [index, hm] of this.state.times.entries()) {
let hour = hm.split(':')[0];
this.state.hour.push(hour);
let minute = hm.split(':')[1];
this.state.minute.push(minute);
this.state.items.push(
<React.Fragment key={index}>
<Button className = 'remove-time'
title = 'x'
times = {this.state.times} updateItems={(e) => this.updateItems(e)}/>
<HM refs = 'hour' time = {this.state.hour[index]} className = 'hour' indexHour = {index} updateHM = {(e) => this.updateHM()}/>
<HM refs = 'minute' time = {this.state.minute[index]} className = 'minute' indexMinute = {index} updateHM = {(e) => this.updateHM()}/>
<Button className = 'add-time'
title = '+'
times= {this.state.times}
updateItems={(e) => this.updateItems(e)}/>
<br/>
</React.Fragment>
)
}
return (
<React.Fragment>
{this.state.items}
</React.Fragment>
)
}
}
class HM extends React.Component {
constructor(props) {
super(props);
}
click(e) {
this.props.updateHM;
debugger;
let HM = e.target.className;
let val = e.target.valueAsNumber;
debugger;
this.props.updateHM(HM,val)
}
render() {
return (
<input type='number'
className = {this.props.className}
value={this.props.time}
onChange={(e) => this.click(e,this.props.time)}/>
)
}
}
答案 0 :(得分:1)
您不能直接访问和修改父元素的道具。取而代之的是,您必须将一个函数(用于修改父级的状态)从父级传递到子级,然后在子元素中调用该函数。
父元素:
<HM ... updateHM={(time, val) => this.updateHM(time, val)} />
儿童元素:
click(e, time) {
...
this.props.updateHM(this.props.refs, time);
}