如何在子组件的构造函数中等待父组件的道具

时间:2019-01-21 09:01:37

标签: reactjs

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

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

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

ChildComponent:

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;

1 个答案:

答案 0 :(得分:1)

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

更多详细信息,请点击此处Detail