将反应表行数据传递给反应模式 [英] Passing react-table row data to react-modal

查看:49
本文介绍了将反应表行数据传递给反应模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

import React, { Component, Fragment } from 'react';import { Button, Modal, ModalHeader, ModalBody, Form, FormGroup, Input, Label } from 'reactstrap';从 'axios' 导入 Axios;类 CompanyModal 扩展组件 {构造函数(道具){超级(道具);this.state = {模态:props.initialModalState,ID: '',标题: '',地址: '',电话号码 : '',电子邮件: ''};this.toggle = this.toggle.bind(this);}componentDidMount() {如果(this.props.company){const { id, title, address, phoneNumber, email } = this.props.companythis.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/companys/Create', this.state).then(res => {console.log(res)}).catch(错误=> {控制台日志(错误)})}提交编辑 = e =>{e.preventDefault()axios.put(`localhost:44394/api/companies/update/${this.state.id}`, this.state).then(res => {控制台日志(res)}).catch(错误=> {控制台日志(错误)})}切换(){this.setState({模态:!this.state.modal});}使成为() {const isNew = this.props.isNew;let title = '编辑公司';让按钮 = '';如果(是新的){title = '添加公司';按钮 = <按钮颜色=成功"onClick={this.toggle}style={{ minWidth: "200px" }}>添加公司</Button>;} 别的 {按钮 = <按钮className="btn-icon btn-round"大小=sm"颜色=警告"onClick={this.toggle}><i className="fa fa-edit"/></按钮>;}返回<片段>{按钮}<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}><ModalHeader toggle={this.toggle}>{title}</ModalHeader><模态体><表单 onSubmit={this.props.company ?this.submitEdit : this.submitNew}><表单组><Label for="name">名称:</Label><Input type="text" name="title" onChange={this.onChange} value={this.state.Title === '' ?'' : this.state.Title}/></FormGroup><表单组><Label for="address">地址:</Label><Input type="text" name="address" onChange={this.onChange} value={this.state.address === null ?'' : this.state.company}/></FormGroup><表单组><Label for="phoneNumber">电话号码:</Label><Input type="number" name="phoneNumber" onChange={this.onChange} value={this.state.phoneNumber === null ?'' : this.state.phoneNumber}/></FormGroup><表单组><Label for="email">电子邮件:</Label><Input type="email" name="email" onChange={this.onChange} value={this.state.email === null ?'' : this.state.email}/></FormGroup><Button type="submit">Submit</Button></表格></ModalBody></模态></片段>;}}导出默认 CompanyModal;

表格代码

<预><代码>import React, { Component } from "react";从反应表"导入反应表;从../Forms/CompanyModal"导入 CompanyModal;从axios"导入 axios;进口 {卡片,卡体,卡头,卡片标题,排,科尔,按钮,按钮工具栏来自反应带";无功数据class CompanyTable 扩展了 React.Component {构造函数(道具){超级(道具);this.state = {帖子:[]};}componentDidMount(){axios.get(`https://localhost:44394/api/companies`).then(res => {const 帖子 = res.data;this.setState({posts});})}使成为() {const 帖子 = this.props.posts;常量列 =[{标题:身份证",访问者:id",显示:假},{标题:姓名",访问者:标题"},{标题:地址",访问者:地址"},{标题:电话号码",访问者:电话号码"},{标题:行动",单元格:道具 =>{返回 (<div className="actions-right"><CompanyModal/><div/>)},可排序:假,可过滤:假}]返回 (<><行><Col xs={12} md={12}><卡片><卡片头><CardTitle tag="h4">公司</CardTitle><CompanyModal isNew/></卡片头><卡片体><反应表数据={this.state.posts}可过滤的列 = {列}默认页面大小={10}显示分页顶部showPaginationBottom={false}className="-striped -highlight"/></CardBody></卡片></Col></行></>);}}导出默认公司表;

解决方案

您可以使用 componentDidUpdate 用于模态组件观察道具变化并设置状态.

(componentWillReceiveProps 现已弃用)

假设你想将 prop exampleProp 从 table view 传递到 modal view:

class CompanyModal 扩展组件 {构造函数(道具){超级(道具);this.state = {示例状态:'东西'//... 其他状态};}...其他代码componentDidUpdate(nextProps) {if (nextProps.exampleProp !== this.props.exampleProp) {//新的道具值this.setState({exampleState: nextProps.exampleProp})}}...其他代码

在您的表格视图中:

标题:行动",单元格:道具 =>{返回 (<div className="actions-right"><CompanyModal exampleProp={this.state.yourTableViewState}/><div/>)},可排序:假,可过滤:假}

Being new to React, I'm having a hard time to pass data from react-table to an "edit" modal and can't seem to find a solution for a similar problem. Data are fetched from the database by an Axios API call and rendered in a react-table. I need to pass data of a rendered row to a modal, in order to then make a put request and update the data to the server. The edit button is in the modal class and then rendered on the table.

Below you can see the modal&form class, which is then called in the 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 code


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;

解决方案

You can use componentDidUpdate for the modal component to watch the props change and set the state.

(componentWillReceiveProps is now deprecated)

Suppose you want to pass prop exampleProp from the table view to the modal view:

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

In your table view:


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

这篇关于将反应表行数据传递给反应模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆