gpt4 book ai didi

javascript - 从子组件更新父组件的状态

转载 作者:行者123 更新时间:2023-11-30 19:26:00 25 4
gpt4 key购买 nike

无法正确更改 props parent。

我不知道怎样做才是对的。

如果有任何帮助,我将不胜感激。

 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)}/>
)
}
}

最佳答案

您不能直接访问和修改父元素的属性。相反,您必须将一个函数(修改父级的状态)从父元素传递给子元素,然后在子元素中调用该函数。

父元素:

<HM ... updateHM={(time, val) => this.updateHM(time, val)} />

子元素:

click(e, time) {
...
this.props.updateHM(this.props.refs, time);
}

关于javascript - 从子组件更新父组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56904631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com