在反应中将子组件的ID传递给父组件

时间:2019-07-14 16:09:37

标签: reactjs

我有两个js文件,结构类似于

App.js ---> Booking.js

bookings.js中有两个文本区域,我想将预订中的ID传递给应用,并在App.js中处理我的数据,这是下面的代码

App.js

        import React, { Component } from "react";
        import Bookings from "./components/Bookings";
        import Meals from "./components/Meals";
        import Error from "./components/Error";

        Date.prototype.addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
        };

        class App extends Component {
        constructor() {
            super();
            this.state = {
            hackers: "",
            dateRange: "",
            error: false,
            errorMessage: [],
            schedule: []
            };
        }
        handleGuestInfo = event => {
            const { id, value } = event.currentTarget;
            this.setState({
            [id]: value
            });
        };

        handleDateInfo = event => {
            const { id, value } = event.currentTarget;
            this.setState({
            [id]: value
            });
        };

        dateFormatCheck(date) {
            let dateChecker = /^(?:(19|20)[0-9]{2})[-.](0[1-9]|1[012])[-.](0[1-9]|[12][0-9]|3[01])$/; //YYYY/MM-DD format
            if (
            dateChecker.test(date.split("to")[0]) &&
            dateChecker.test(date.split("to")[1])
            ) {
            return true;
            }
            return false;
        }

        reset() {
            this.setState({
            error: false,
            errorMessage: "",
            errorData: [],
            schedule: []
            });
        }

        handleMealSchedule() {
            //this.reset();
            let hackers = this.state.hackers.split("\n");
            let dateRange = this.state.dateRange.split("\n");
            let errorData = [];
            let scheduleData = [];
            if (hackers.length === dateRange.length) {
            for (let i = 0; i < hackers.length; i++) {
                if (this.dateFormatCheck(dateRange[i])) {
                let startDay = dateRange[i].split("to")[0];
                let endDay = dateRange[i].split("to")[1];

                let noOfDays = this.getDifferenceInDays(startDay, endDay);
                for (let j = 0; j < noOfDays.length; j++) {
                    scheduleData.push(
                    "Breakfast for " + hackers[i] + " on " + noOfDays[j]
                    );
                    scheduleData.push("Lunch for " + hackers[i] + " on " + noOfDays[j]);
                    scheduleData.push(
                    "Dinner for " + hackers[i] + " on " + noOfDays[j]
                    );
                }
                } else {
                errorData.push("Meal data not available for " + hackers[i]);
                }
            }
            } else {
            errorData.push("Hackers and Date Range length mismatch");
            }

            if (errorData.length > 0) {
            this.setState({
                error: true,
                errorMessage: errorData
            });
            }
            this.setState({
            schedule: scheduleData
            });
        }

        getDifferenceInDays(startDate, endDate) {
            let dateArray = [];
            let currentDate = new Date(startDate);
            while (currentDate <= new Date(endDate)) {
            dateArray.push(new Date(currentDate).toLocaleDateString());
            currentDate = currentDate.addDays(1);
            }
            return dateArray;
        }
        render() {
            const { error, errorMessage, schedule } = this.state;

            return (
            <div className="container-fluid">
                <center>
                <h2>Hacker Hostel</h2>
                </center>
                <div className="container">
                <Bookings
                    onHackerChange={e => this.handleGuestInfo(e)}
                    onDateChange={e => this.handleDateInfo(e)}
                    onButton={this.handleMealSchedule}
                    hackerid={this.state.hackers}
                    daterangeid={this.state.dateRange}
                />
                {error ? <Error errorMessage={errorMessage} /> : null}
                {/* <Meals /> */}
                </div>
            </div>
            );
        }
        }

        export default App;

Booking.js

    import React, { Component } from "react";

    import TextField from "@material-ui/core/TextField";
    import Button from "@material-ui/core/Button";

    class Bookings extends Component {
    render() {
        return (
        <div className="row">
            <TextField
            className="col-md-6"
            multiline
            rows="4"
            id={this.props.hackerid}
            placeholder="Enter the hacker list (one hacker per line)"
            onChange={this.props.onHackerChange}
            />
            <TextField
            className="col-md-6"
            multiline
            rows="4"
            id={this.props.daterangeid}
            onChange={this.props.onDateChange}
            placeholder="Enter the date range for each hacker's stay (one range per line)"
            />
            <Button
            variant="outlined"
            color="primary"
            className="block-center"
            onClick={this.props.onButton}
            >
            Get Meals Schedule
            </Button>
        </div>
        );
    }
    }

    export default Bookings;

关于如何执行此操作的任何想法?这两个textarea ID将从预订传递到app.js,在此必须完成我的所有验证。

1 个答案:

答案 0 :(得分:0)

您将必须通过使用App中的状态来控制TextField值,并将其作为道具传递给Booking组件。也不需要ID。

在App组件中,您可以使用onChange函数来更新State值,例如:

  handleDateInfo = event => {
        const { id, value } = event.currentTarget;
        this.setState({
         DateRangeValue: value
        });
    };

在预订部分中,将是这样的:

<TextField
        className="col-md-6"
        multiline
        rows="4"
        value={this.props.DateRangeValue}
        onChange={this.props.onDateChange}
        placeholder="Enter the date range for each hacker's stay (one range per line)"
        />

还要突出显示@Aprillion的注释,这将使TextFields controlled components。您可以在链接中阅读有关这些内容的更多信息。简而言之,它将状态作为文本字段的源值。要更新文本字段值,您还必须同时更新其状态。