将 react-table 行数据传递给 react-modal

Passing react-table row data to react-modal

作为 React 的新手,我很难将数据从 react-table 传递到 "edit" 模态,并且似乎无法找到类似问题的解决方案。数据通过 Axios API 调用从数据库中获取并在 react-table 中呈现。我需要将呈现行的数据传递给模态,然后发出放置请求并将数据更新到服务器。编辑按钮在模式 class 中,然后在 table.

上呈现

下面你可以看到模态&形式class,然后在table class.

中调用
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;

Table代码


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来观察道具变化和设置状态。

componentWillReceiveProps 现已弃用)

假设您要将 exampleProp 从 table 视图传递到模态视图:

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

在您的 table 视图中:


        Header: "Actions",
        Cell: props =>{
          return ( 
            <div className="actions-right">
            <CompanyModal exampleProp={this.state.yourTableViewState} />
            <div/>
          )
        },
        sortable: false,
        filterable: false
       }

我通过这样做使用钩子解决了这个问题:

const [show, setShow] = useState(false);
const [selectedRow, setSelectedRow] = useState({});

const handleClose = () => setShow(false);
const handleShow = (selected) => {
  setSelectedRow(selected);
  setShow(true);
  };

我创建了一个 useState 变量来包含点击了哪一行;然后使用 setter 更新状态变量。

唯一棘手的事情是从 react-table 获取原始行数据,但最终变得非常简单。

在组件中(或任何你想触发模态显示的地方),添加一个 onClick 属性并传递你的 handleShow row.original 以获取所有数据。

<tbody className='body' {...getTableBodyProps()}>
              {page.map((row, i) => {
                prepareRow(row);
                return (
                  <Fragment key={row.getRowProps().key}>
                    <tr className='tr' onClick={() =>   handleShow(row.original)}>
                      {row.cells.map((cell) => {
                        return (
                          <td className='td' {...cell.getCellProps()}>
                            {cell.render("Cell")}
                          </td>
                        );
                      })}
                    </tr>
                  </Fragment>
                );
              })}
            </tbody>

我们可以从 .map 函数访问创建 table 行的行。在我的示例中,我使用的是分页,因此您映射的内容可能会有所不同。无论如何,该行应该可供您使用。

该行的其他可用属性是:

allCells: (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
cells: (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
depth: 0
getRowProps: ƒ (userProps)
id: "1"
index: 1
original: {processing_agent: "Smitty", log_id: "ASDJFEIF87ASDF", date_created: "2020-08-12 02:39:13+00:00", log_amount: "0.06", company_name: "Kinkos", …}
originalSubRows: []
subRows: []
values: {processing_agent: "Smitty", log_id: "ASDJFEIF87ASDF", company_name: "Kinkos", invoice_count: "1", merchant_log_status: "UNKNOWN", …}
__proto__: Object