【问题标题】:How to wait for props of the parent component in the constructor of the child component如何在子组件的构造函数中等待父组件的props
【发布时间】:2019-06-14 15:11:24
【问题描述】:

我创建了一个能够添加笔记的日历应用。为了实现添加注释的功能,我创建了一些父组件,它有自己的状态timeStart,然后传递给子组件。子组件应该接受来自ParentComponentprops 在构造函数中执行time1:this.props.timeStart。但是由于 setState 函数 asynchronous ChildComponent 没有时间等待 ParentComponent 的 props。

如何设置 ChildComponent 的初始状态等待来自 ParentComponent 的道具(换句话说,同步)?

父组件:

class ParentComponent extends React.Component {

 constructor() {
    super();
    this.state = {
        timeStart:'00:00',
 };

 render(){

    //some code for changing this.state.timeStart

    return (<ChildComponent timeStart={this.state.timeStart}/>);
 }
}

子组件:

class ChildComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            time1:this.props.timeStart,
            time2:'00:00',
        };
        this.onTime1Change = this.onTime1Change.bind(this);
        this.onTime2Change = this.onTime2Change.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onSubmit(event){
        let el ={
            task:this.state.task.slice(),
            time1:this.state.time1.slice(),
            time2:this.state.time2.slice()
        };
        events.push(el);
        event.preventDefault();
    }


    onTime1Change(event){
        this.setState({time1: event.target.value});
    }

    onTime2Change(event){
        this.setState({time2: event.target.value});
    }

    render() {
        return (
            <div className="form">
                   <form onSubmit={this.onSubmit}>
                    <p><label><input type="time" step="3600" name="time1" value={this.state.time1}
                                                           onChange={this.onTime1Change}/></label>
                       <label><input type="time" step="3600" name="time2" value={this.state.time2}
                                                       onChange={this.onTime2Change}/></label></p>

                    <p><input type="submit" value="Submit" /></p>
                </form>
            </div>
        );
    }
}

export default ChildComponent;

【问题讨论】:

标签: reactjs


【解决方案1】:

可以使用组件的生命周期方法getDerivedStateFromProps来实现。

更多详情请点击此处Detail

【讨论】:

  • 你帮助了我!谢谢
猜你喜欢
  • 2019-09-28
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 2020-03-30
相关资源
最近更新 更多