将反应表行数据传递给反应模式

2023-12-03

作为 React 新手,我很难将数据从反应表传递到“编辑”模式,并且似乎无法找到类似问题的解决方案。数据通过 Axios API 调用从数据库中获取并呈现在反应表中。我需要将渲染行的数据传递到模式,以便随后发出放置请求并将数据更新到服务器。编辑按钮位于模态类中,然后呈现在表格上。

下面你可以看到 modal&form 类,然后在 table 类中调用它。

import React, { Component, Fragment } from 'react';
import { Button, Modal, ModalHeader, ModalBody, Form, FormGroup, Input, Label } from 'reactstrap';
import Axios from 'axios';


class CompanyModal extends Component {
    constructor(props) {
        super(props);
    this.state = {
        modal: props.initialModalState,
        id: '',
        title: '',
        address: '',
        phoneNumber : '',
        email: ''
    };
    this.toggle = this.toggle.bind(this);
}

componentDidMount() {
    if (this.props.company) {
        const { id, title, address, phoneNumber, email } = this.props.company
        this.setState({ id,title, address, phoneNumber, email});
    }
}
onChange = e => {
    this.setState({ [e.target.name]: e.target.value })
}


submitNew = e => {
    e.preventDefault()
    Axios.post('localhost:44394/api/companies/Create', this.state)
    .then(res => {
    console.log(res)})
    .catch(error => {
        console.log(error)
    })
}

submitEdit = e =>{
    e.preventDefault()
    Axios.put(`localhost:44394/api/companies/update/${this.state.id}`, this.state)
    .then(res => {
        console.log(res)
    })
    .catch(error => {
        console.log(error)
    })
}
    toggle () {
        this.setState({
            modal: !this.state.modal
        });
    }

    render() {
        const isNew = this.props.isNew;

        let title = 'Edit Company';
        let button = '';
        if (isNew) {
            title = 'Add Company';

            button = <Button
                color="success"
                onClick={this.toggle}
                style={{ minWidth: "200px" }}>Add Company</Button>;
        } else {
            button = <Button
                className="btn-icon btn-round"
                size="sm"
                color="warning"
                onClick={this.toggle}><i className="fa fa-edit" />
                </Button>;
        }

        return <Fragment>
            {button}
            <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
                <ModalHeader toggle={this.toggle}>{title}</ModalHeader>
                <ModalBody>
                    <Form onSubmit={this.props.company ? this.submitEdit : this.submitNew}>
                        <FormGroup>
                            <Label for="name">Name:</Label>
                            <Input type="text" name="title" onChange={this.onChange} value= 
                                 {this.state.Title === '' ? '' : this.state.Title} />
                        </FormGroup>
                        <FormGroup>
                            <Label for="address">Address:</Label>
                            <Input type="text" name="address" onChange={this.onChange} value= 
                                 {this.state.address === null ? '' : this.state.company} />
                        </FormGroup>
                        <FormGroup>
                            <Label for="phoneNumber">Phone Number:</Label>
                            <Input type="number" name="phoneNumber" onChange={this.onChange} value= 
                                 {this.state.phoneNumber === null ? '' : this.state.phoneNumber} />
                        </FormGroup>
                        <FormGroup>
                            <Label for="email">Email:</Label>
                            <Input type="email" name="email" onChange={this.onChange} value= 
                                 {this.state.email === null ? '' : this.state.email} />
                        </FormGroup>
                        <Button type="submit">Submit</Button>
                    </Form>
                </ModalBody>
            </Modal>
        </Fragment>;
    }
    }
export default CompanyModal;

表代码


import React, { Component } from "react";
import ReactTable from "react-table";
import CompanyModal from "../Forms/CompanyModal";
import axios from "axios";
import {
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Row,
  Col,
  Button,
  ButtonToolBar
} from "reactstrap";

 var data

class CompanyTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts:[]
    };
  }


componentDidMount(){
  axios.get(`https://localhost:44394/api/companies`)
  .then(res => {
    const posts = res.data;
    this.setState({posts});
  })
}

  render() {
    const posts = this.props.posts;
    const columns =[
      {
        Header: "Id",
        accessor: "id",
        show: false
      },
      {
        Header: "Name",
        accessor: "title"
      },
      {
        Header: "Address",
        accessor: "adress"
      },
      {
        Header: "Phone Number",
        accessor: "phoneNumber"
      },
      {
        Header: "Actions",
        Cell: props =>{
          return ( 
            <div className="actions-right">




            <CompanyModal/>





            <div/>
          )
        },
        sortable: false,
        filterable: false
       }
    ]
    return (
      <>      
          <Row>
            <Col xs={12} md={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Companies</CardTitle>
                  <CompanyModal isNew/>
                </CardHeader>
                <CardBody>
                  <ReactTable
                    data={this.state.posts}
                    filterable
                    columns = {columns}
                    defaultPageSize={10}
                    showPaginationTop
                    showPaginationBottom={false}
                    className="-striped -highlight"
                    />                 
                </CardBody>
              </Card>
            </Col>
          </Row>          
      </>
    );
  }
}

export default CompanyTable;

您可以使用componentDidUpdate让模态组件观察 props 的变化并设置状态。

(componentWillReceiveProps现已弃用)

假设你想传递 propexampleProp从表格视图到模态视图:

class CompanyModal extends Component {
    constructor(props) {
        super(props);
    this.state = {
        exampleState: 'something'
        // ... other states
    };
}

... other code

componentDidUpdate(nextProps) {

 if (nextProps.exampleProp !== this.props.exampleProp) {// New prop value
this.setState({exampleState: nextProps.exampleProp})
}
}

... other code

在您的表视图中:


        Header: "Actions",
        Cell: props =>{
          return ( 
            <div className="actions-right">
            <CompanyModal exampleProp={this.state.yourTableViewState} />
            <div/>
          )
        },
        sortable: false,
        filterable: false
       }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将反应表行数据传递给反应模式 的相关文章

随机推荐