道具数据在模型对话框中显示未定义

时间:2019-11-27 07:22:50

标签: reactjs material-ui

我正在将Material UI表与reactjs一起使用。在单击该按钮时,我在一列中只有一个按钮,我必须获得一个模型对话框以及该行数据。

以下是母组件 Table.js

//Update button event
handleRepeatUpdate = event => {
  this.refs.updaterepat.handleUpdateOpen();
  let e = event;
  this.setState({
    selected_rowID: e.id,
    selectEvent: e
  });
};

//material table

<MaterialTable
  title=""
  columns={[
    { title: "User Name", field: "userName", lookup: this.state.users },
    {
      title: "Role",
      field: "role",
      value: this.state.userName,
      lookup: {
        Primary: "Primary",
        Secondary: "Secondary",
        Escallation: "Escallation",
        Override: "Override "
      }
    },

    {
      title: "Start Date",
      field: "startDate",
      type: "datetime",
      value: this.state.role
    },
    {
      title: "End Date",
      field: "endDate",
      type: "datetime",
      value: this.state.startDate
    },

    {
      title: "Repeat",
      field: "isrepeat",
      type: "boolean",
      value: this.state.isrepeat,
      render: rowData => (
        <Fragment>
          <Button onClick={() => this.handleRepeatClick(rowData)}>
            <RectangleIcon />
          </Button>
          <Button onClick={() => this.handleRepeatUpdate(rowData)}>
            <EditIcon />
          </Button>
          <Button onClick={() => this.handleDeleteRepeat(rowData)}>
            <DeleteIcon />
          </Button>
        </Fragment>
      )
    }
  ]}
  data={this.state.data}
/>;

<RepeatUpdate ref="updaterepat" repeatrow = {this.state.selected_rowID} seleRow = {this.state.selectEvent}/>

bellow我正在给“模型”对话框页面 RepeatUpdate.js

import React, { Fragment } from "react";
import Button from "@atlaskit/button";
import Modal, { ModalTransition } from "@atlaskit/modal-dialog";
import style from "./style.css";
import { FieldTextStateless } from "@atlaskit/field-text";
import Form, { Field, FormFooter } from "@atlaskit/form";
import DropdownMenu, {
  DropdownItemGroup,
  DropdownItem
} from "@atlaskit/dropdown-menu";
import Select from "@atlaskit/select";
import FieldBase, { Label } from "@atlaskit/field-base";
import axios from "axios";
import { gridSize } from "@atlaskit/theme";
import {
  DatePicker,
  DateTimePicker,
  TimePicker
} from "@atlaskit/datetime-picker";
import { RadioGroup } from "@atlaskit/radio";

const Ends = [
  { value: "Never", label: "Never" },
  { value: "On", label: "On" },
  { value: "After", label: "After" }
];

var Days = [];
for (let i = 1; i <= 31; i++) {
  Days.push({
    label: i,
    id: i,
    value: i
  });
}

var weeknumber = [];
for (let j = 1; j <= 7; j++) {
  weeknumber.push({
    label: j,
    value: j,
    id: j
  });
}

var monthnum = [];
for (let k = 1; k <= 12; k++) {
  monthnum.push({
    label: k,
    value: k,
    id: k
  });
}

var afternum = [];
for (let i = 0; i <= 20; i++) {
  afternum.push({
    label: i,
    value: i
  });
}

//multiselect styling
const customStyles = {
  container(styles) {
    return { ...styles, width: "20%" };
  }
};

const lookup = {
  day: Days,
  week: weeknumber,
  month: monthnum,
  select: []
};

export default class RepeatPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpen: false,
      repeatonevery: "",
      startson: "",
      endsonnever: "",
      repeat: "",
      repeatAfter: "",
      dataValue: "select",
      repeatson: [],
      datetime: "",
      timeform: "",
      numval: "",
      data: "",
      selectdata: ""
    };
  }

  //repeat select
  onChange = ({ target: { value } }) => {
    this.setState({ dataValue: value, repeat: value });
    // console.log("repeat is:",value)
    // console.log("onChange repeat",this.state.repeat)
  };

  // repeat on every
  handleRepeatOn = e => {
    e.persist();
    this.setState({
      repeatonevery: e.target.value,
      data: this.props.respdata.id
    });
    console.log("repeats on :", this.state.repeatonevery);
  };

  //repeat starts on
  handleStartOn = startson => {
    this.setState({
      startson
    });
    console.log("starts on :", startson);
  };

  handleTimeForm = timeform => {
    this.setState({
      timeform
    });
    console.log("timeForm", timeform);
  };

  handleEndChange = event => {
    event.preventDefault();
    this.setState({
      endsonnever: event.target.value
    });
    console.log("handleEnd change", this.state.endsonnever);
  };

  handleSelect = numval => {
    this.setState({
      numval
    });
    console.log("select values", numval);
  };

  handleUpdateSubmit = e => {
    e.preventDefault();
  };

  handleUpdateOpen = event => {
    this.setState({
      isOpen: true,
      selectdata: this.props.repeatrow
      // selctitem : this.props.seleRow
    });
    let schedulesdata = this.props.repeatrow;
    let schedule_user = this.props.seleRow;
    console.log("selectdata :", this.state.selectdata);
    console.log(
      "schedule row data",
      this.props.repeatrow,
      "selected row is",
      this.props.seleRow
    );
  };

  close = () => this.setState({ isOpen: false });

  render() {
    console.log("repeatrow ", this.props.repeatrow);
    const { isOpen } = this.state;
    let self = this;
    const { dataValue } = this.state;
    const options = lookup[dataValue];
    return (
      <div>
        <div>
          <ModalTransition>
            {isOpen && (
              <Modal heading="">
                <Form onSubmit={data => console.log(data)}>
                  {({ formProps }) => (
                    <form {...formProps} name="text-fields">
                      <h2> Repeat</h2>
                      {/* <div className="row">  */}
                      <Field name="Repeat" defaultValue="" label="Repeat">
                        {({
                          fieldProps: { isRequired, isDisabled, ...others }
                        }) => (
                          <select
                            onChange={this.onChange}
                            value={this.state.repeat}
                          >
                            <option value="select">Select</option>
                            <option value="day">Day</option>
                            <option value="week">week</option>
                            <option value="month">Month</option>
                          </select>
                        )}
                      </Field>

                      <Field
                        name="Repeat"
                        defaultValue=""
                        label="Repeats on every"
                      >
                        {({
                          fieldProps: { isRequired, isDisabled, ...others }
                        }) => (
                          <select
                            onChange={this.handleRepeatOn}
                            value={this.state.repeatonevery}
                          >
                            {options.map(o => (
                              <option key={o.id}>{o.label}</option>
                            ))}
                          </select>
                        )}
                      </Field>

                      <div className="row">
                        <Field name="start" defaultValue="" label="Starts On">
                          {({
                            fieldProps: { isRequired, isDisabled, ...others }
                          }) => (
                            <DateTimePicker
                              innerProps={{ style: { width: gridSize() * 20 } }}
                              onChange={this.handleStartOn}
                              value={this.state.startson}
                            />
                          )}
                        </Field>
                      </div>

                      <Field name="end" defaultValue="" label="End">
                        {({
                          fieldProps: { isRequired, isDisabled, ...others }
                        }) => (
                          <div>
                            <div>
                              <label>
                                <input
                                  type="radio"
                                  value="never"
                                  name="never"
                                  style={{ marginLeft: "15px" }}
                                  onChange={this.handleEndChange}
                                />
                                Never
                              </label>
                            </div>
                            <div className="row">
                              <label>
                                <input
                                  type="radio"
                                  name="on"
                                  style={{ marginLeft: "31px" }}
                                  onChange={this.handleEndChange}
                                />
                                on
                              </label>
                              <DateTimePicker
                                innerProps={{
                                  style: { width: gridSize() * 20 }
                                }}
                                onChange={this.handleTimeForm}
                                value={this.state.timeform}
                              />
                            </div>
                            <div className="row">
                              <label>
                                <input
                                  type="radio"
                                  value="after"
                                  name="after"
                                  style={{ marginLeft: "31px" }}
                                  onChange={this.handleEndChange}
                                />
                                After
                              </label>
                              <Select
                                className="single-select selectwidth"
                                classNamePrefix="react-select"
                                options={afternum}
                                value={this.state.numval}
                                onChange={this.handleSelect}
                                // styles = {customStyles}
                              />

                              <label>Occurences</label>
                            </div>
                          </div>
                        )}
                      </Field>

                      <FormFooter>
                        <Button
                          type="submit"
                          appearance="primary"
                          onClick={this.handleUpdateSubmit}
                        >
                          Submit
                        </Button>
                        <Button className="BtnspaceP" onClick={this.close}>
                          Close
                        </Button>
                      </FormFooter>
                    </form>
                  )}
                </Form>
              </Modal>
            )}
          </ModalTransition>
        </div>
      </div>
    );
  }
}

我没有在RepeatUpdate.js组件的handleUpdateOpen()事件中获取道具数据。 使用componentWillReceiveProps时,我正在获取数据,但在该事件中我需要数据。

谢谢

1 个答案:

答案 0 :(得分:0)

我认为您应该在Table.js状态下保留opened属性,并将其作为prop传递给RepeatUpdate而不是调用this.refs.updaterepat.handleUpdateOpen();,因为这只是一个坏模式-做某事可以带道具的时候带裁判。

然后使用getDerivedStateFromProps在RepeatUpdate中处理this.props,例如:

// for RepeatUpdate.js
static getDerivedStateFromProps(state, props) {
 if(props.isOpen && props.isOpen !== state.isOpen) {
  return {...state, isOpen: props.isOpen};
 }
 return state;
}

基本上,我认为您没有在handleUpdateOpen中获得道具,因为您丢失了上下文(调用thisthis.refs.updaterepat.handleUpdateOpen()是未定义的)。 为了避免这种情况,您可以将handleUpdateOpen从arrow函数更改为函数声明,并在构造函数中绑定上下文:

 constructor(props) {
    super(props);
    this.state = {
      isOpen: false,
      repeatonevery: "",
      startson: "",
      endsonnever: "",
      repeat: "",
      repeatAfter: "",
      dataValue: "select",
      repeatson: [],
      datetime: "",
      timeform: "",
      numval: "",
      data: "",
      selectdata: ""
    };
   this.handleUpdateOpen = this.handleUpdateOpen.bind(this);
  }

  function handleUpdateOpen(){...}

之后this.props将可用