簡體   English   中英

在React中將數據從子組件傳遞到父組件

[英]Pass data from child component to parent component in React

我目前正在構建一個簡單的React應用程序。 我有一些數據從laravel應用程序傳遞到window.example對象。 然后,我想訪問數據,並且我發現最初可以使用props來做。 但是問題是,當我在AssignmentForm組件中提交表單時,我想更新顯示數據的AssignmentBox中的數據,並添加一行數據。 我該怎么辦?

所以我的結構看起來像這樣:

  • DashboardApp
    • 分配箱
    • AssignmentFormNew

這是我的代碼:

main.js:

import swal from 'sweetalert';
import $ from 'jquery';
import React from 'react';
import { render } from 'react-dom';
import DashboardApp from './components/Dashboard';

render(
    <DashboardApp tracks={window.tracks} assignments={window.assignments} />,
    document.getElementById('content')
);

Dashboard.js:

import React from 'react';
import {Grid, Row, Col} from 'react-bootstrap';
import TrackBox from './TrackBox';
import TrackFormStop from './TrackFormStop';
import TrackFormNew from './TrackFormNew';
import AssignmentBox from './AssignmentBox';
import AssignmentFormNew from './AssignmentFormNew';

class DashboardApp extends React.Component {
    render () {
        return (
            <Grid>
                <Row>
                    <Col md={12}>
                        <AssignmentBox assignments={this.props.assignments} />
                        <AssignmentFormNew />
                    </Col>
                </Row>
            </Grid>
        )
    }
}

export default DashboardApp;

AssignmentBox.js

import React from 'react';
import {Panel} from 'react-bootstrap';

const title = (
  <h2>Current Assignments</h2>
);

class AssignmentBox extends React.Component {
    render () {
        return (
            <Panel header={title}>
                <ul>
                    {this.props.assignments.map(item => (
                        <li key={item.id}><a href="assignment/{item.slug}">{item.title}</a></li>
                    ))}
                </ul>
            </Panel>
        )
    }
}

export default AssignmentBox;

AssignmentFormNew.js

import React from 'react';
import {Panel, Button, FormGroup, ControlLabel} from 'react-bootstrap';
import $ from 'jquery';

const title = (
    <h2>New Assignment</h2>
);

const footer = (
    <Button bsStyle="primary" type="submit" block>New Assignment</Button>
);

class AssignmentFormNew extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            title: '',
            description: '',
            customer: '',
            date: ''
        };

        this.handleSubmit = this.handleSubmit.bind(this);

        this.handleTitleChange = this.handleTitleChange.bind(this);
        this.handleDescriptionChange = this.handleDescriptionChange.bind(this);
        this.handleCustomerChange = this.handleCustomerChange.bind(this);
        this.handleDeadlineChange = this.handleDeadlineChange.bind(this);
    }

    handleSubmit (e) {
        e.preventDefault();

        console.log(window.Laravel.csrfToken);

        $.ajax({
            url: '/assignment',
            type: 'POST',
            data: {
                _token: window.Laravel.csrfToken,
                title: this.refs.title.value,
                description: this.refs.description.value,
                customer: this.refs.customer.value,
                deadline: this.refs.deadline.value
            },
            success: res => {
                this.setState({
                    title: '',
                    description: '',
                    customer: '',
                    deadline: ''
                });

                console.log(res);
            },
            error: (xhr, status, err) => {
                console.error(status, err.toString());
            }
        });
    }

    handleTitleChange (event) {
        this.setState({title: event.target.value});
    }

    handleDescriptionChange (event) {
        this.setState({description: event.target.value});
    }

    handleCustomerChange (event) {
        this.setState({customer: event.target.value});
    }

    handleDeadlineChange (event) {
        this.setState({deadline: event.target.value});
    }

    render () {
        return (
            <form onSubmit={this.handleSubmit}>
                <Panel header={title} footer={footer}>
                    <FormGroup controlId="assignmentTitle">
                        <ControlLabel>Title</ControlLabel>
                        <input type="text" ref="title" placeholder="e.g. Crowdfunding module for prestashop" className="form-control" value={this.state.title} onChange={this.handleTitleChange} />
                    </FormGroup>
                    <FormGroup controlId="assignmentDescription">
                        <ControlLabel>Description</ControlLabel>
                        <textarea className="form-control" ref="description" rows="10" value={this.state.description} onChange={this.handleDescriptionChange} />
                    </FormGroup>
                    <FormGroup controlId="assignmentCustomer">
                        <ControlLabel>Customer</ControlLabel>
                        <input type="text" placeholder="e.g. John Doe" ref="customer" className="form-control" value={this.state.customer} onChange={this.handleCustomerChange} />
                    </FormGroup>
                    <FormGroup controlId="assignmentDeadline">
                        <ControlLabel>Deadline</ControlLabel>
                        <input type="date" className="form-control" ref="deadline" value={this.state.deadline} onChange={this.handleDeadlineChange} />
                    </FormGroup>
                </Panel>
            </form>
        )
    }
}

export default AssignmentFormNew;

先感謝您。

將handleSubmit()函數放入Dashboard.js中,並添加以下代碼

 constructor (props) {
        super(props);
        this.state = {
            assignments:this.props.assignments
        };
}

handleSubmit (e) {
  ... your ajax code
  this.setState({assignments:res})
}

<AssignmentBox assignments={this.state.assignments} handleSubmit={this.handleSubmit}/>

然后在AssignmentFormNew.js中更改:

<form onSubmit={this.props.handleSubmit}>

基本上,當您單擊提交時,它將在Dashboard.js中調用父級的handleSubmit函數,然后在您的ajax調用之后,更新狀態,以便AssignmentBox將使用新數據重新呈現它。

在分配框中創建一個方法來更新數據,並將該功能作為道具傳遞給分配表單。 在賦值表單中調用該函數並傳遞數據。

在AssignmentFormNew.js中

handleSubmit (e) {
    e.preventDefault();
    this.props.childValuesToParent(e);  
  .....
}

現在該道具可在父級內部使用-Dashboard.js像這樣

<AssignmentFormNew childValuesToParent={this.handleChange} />

有點像回電。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM