从子组件到父组件的React句柄数据

时间:2018-01-30 16:17:49

标签: javascript reactjs ecmascript-6 material-ui

我的反应非常新,也是材料 - 我和我试图弄脏手。我试图将一些数据从子组件传递到父组件,以便更新 delivery-at 的父状态,新的日期正在控制台上打印,但是状态并没有。更新。

class TaskForm extends React.Component {
      constructor(props) {
        super(props);

        this.state = {
          formData: {
            delivery_at: null,
          }
        };
        this.handleDateChange = this.handleDateChange.bind(this);
      }
    handleDateChange = (event, date) => {
        this.setState({
          formData: {
            delivery_at: date
          }
        });
        console.log(date);
      };
      render() {
        const { formData, submitted } = this.state; 
        return (
          <div>
            <ValidatorForm
              style={formStyle}
              ref="form"
              onSubmit={this.handleSubmit}
            >
              <DateCalendar //Datepicker child component
                name="delivery_at"
                value={formData.delivery_at}
                handleChange={this.handleDateChange}
                validators={["required"]}
              />
              <RaisedButton
               onClick={() => this.handleSubmit()}
               type="submit"
               label={
               (submitted && "Your form is submitted!") ||
               (!submitted && "Submit")
               }
               disabled={submitted}
               backgroundColor="pink"
          />
        </ValidatorForm>
          </div>
        );
      }
    }

子组件

import React from "react";
import DatePicker from "material-ui/DatePicker";

class DateCalendar extends React.Component {

render() {
    // const{ delivery_at } = this.state;
    return (
      <DatePicker
        hintText="Delivery At"
        name={this.props.name}
        value={this.props.delivery_at}
        autoOk={true}
        onChange={this.props.handleChange}
      />
    );
  }
}

export default DateCalendar;

1 个答案:

答案 0 :(得分:0)

编辑** 坚持下去 - 我会想出来

我不确定但是尝试改变你的方法看起来像这样(这可能是&#34的价值问题;这个&#34;:

      handleDateChange(event, date){
        this.setState({
          formData: {
            delivery_at: date
          }
        });
        console.log(date);
      };

进一步调试尝试在回调中记录状态:

      handleDateChange(event, date){
        this.setState({
          formData: {
            delivery_at: date
          }
        }, () => {
            console.log(this.state)
        });
        console.log(date);
      };