自在猫先生 2023-06-13 10:57 采纳率: 62.9%
浏览 42
已结题

React根据接收到的数组对象数据动态展示到table表格中

我从子组件中读取数据到父组件,需要在父组件中的table表格中动态的进行展示
以下是父组件中的部分代码,我在展示的时候遇到了问题无法进行展示

变量定义
const [basicMeta,setBasicMeta]=useState(null);
const [columntwoData, setColumntwoData] = useState([]);
列定义
  const [columntwo, setcolumntwo] = useState([
        {
          title: '表名',
          dataIndex: 'tablename',
          key: 'tablename',
        },
        {
          title: '属性',
          dataIndex: 'attributes',
          key: 'attributes',
        },
        {
          title: '英文名',
          dataIndex: 'en_name',
          key: 'en_name',
        },
        {
          title: '中文名',
          dataIndex: 'zh_name',
          key: 'zh_name',
        },
        {
          title: '字段',
          dataIndex: 'fields',
          key: 'fields',
        },
        {
          title: '长度',
          dataIndex: 'length',
          key: 'length',
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '类型',
          dataIndex: 'type',
          key: 'type',
        },,
      ]);

    //读取父组件api接口数据并赋值给定义的变量
const docMetaSave=(formData,selectedCollection)=>{
  debugger
 console.log(selectedCollection);
 setBasicMeta({...formData});
}
读取到的数据格式如下:
basicMeta数据格式:
selectedRows
: Array(11)
0: {key: 1, value: '字段'}
1: {key: 2, value: ' PushLine'}
2: {key: 3, value: ' name'}
3: {key: 4, value: ' PushName'}
4: {key: 5, value: ' PushName'}
5: {key: 6, value: ' 09f21006-a440-48fe-d5f1-08db68911080'}
6: {key: 7, value: ' 300'}
7: {key: 8, value: ' 名称'}
8: {key: 9, value: ' nvarchar'}
9: {key: 10, value: ' 名称'}
10: {key: 11, value: 'PushLine'}

读取数据赋值给定义的变量动态生成行

useEffect(() => {
  if (!basicMeta || !basicMeta.selectedRows) {
    setColumntwoData([]);
    return;
  }

  debugger
  const selectedTable = basicMeta.selectedRows.find(row => row.value === 'table_name');

  const titleMap = {
    'table_name': '表名',
    'attributes': '属性',
    'en_name': '英文名',
    'zh_name': '中文名',
    'fields': '字段',
    'length': '长度',
    'name': '名称',
    'type': '类型',
  };
  const newColumns = basicMeta.selectedRows.map(row => ({
    title: titleMap[row.value],
    dataIndex: row.value,
    key: row.key
  }));

  const newTableData = {};
  debugger
  basicMeta.selectedRows.forEach(row => {
    
    basicMeta.selectedRows.forEach(row => {
      newTableData[row.value] = row.value;
    });
    
    
  });

  const newColumntwoData = [{
    ...newTableData,
    key: 'columntwo'
  }];

  setcolumntwo(newColumns);
  setColumntwoData(selectedTable ? newColumntwoData : []);
}, [basicMeta]);

界面渲染
  <Table
                dataSource={columntwoData}
                columns={columntwo}
                />
  • 写回答

2条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-06-13 12:23
    关注
    import React from 'react'
    import { observer } from 'mobx-react'
    import { Table, Input, Select, Form, Button } from 'antd'
    import $state from './state'
    
    const { Option } = Select
    const { Item } = Form
    @observer
    class ThirdTable extends React.Component {
      constructor(props) {
        super(props)
        this.state = {}
      }
    
      componentDidMount() {
        $state.queryDetails()
        this.isDisable()
      }
      componentDidUpdate() {
        this.isDisable()
      }
    
      //判断按钮是否是禁止状态
      isDisable = () => {
        let source = [];
        source = $state.topThreeDTO || []
    
        if (!source.length) {
          $state.isDisableFlag1 = false
        } else {
          $state.isDisableFlag1 = true
        }
        //优化后为下面这样
        $state.isDisableFlag1=!!source.length
      }
    
      init = () => {
        const { getFieldDecorator } = this.props.form
        const projectArr = [
          { name: "绿州", num: "100" },
          { name: "长岛", num: "101" },
          { name: "紫荆", num: "102" }
        ]
    
        this.columns = [
          {
            title: '排名',
            dataIndex: 'orderNum',
          },
          {
            title: '项目名称',
            dataIndex: 'projectName',
            width: '40%',
            render: (text, record) => {
              console.log(`projectName.${record.orderNum}`)//projectName.1 需要保证唯一性
              return <Item>
                {     
                  getFieldDecorator(`projectName.${record.orderNum}`, {
                    initialValue: text && text.num
                  })
                    (
                      <Select>
                        {
                          projectArr.length > 0 && projectArr.map((item, index) => {
                            return <Option style={{width:120}} value={item.num} key={index}>			{item.name}</Option>
                          })
                        }
                      </Select>
                    )
                }
              </Item>
            }
          },
          {
            title: '均价(元/㎡)',
            dataIndex: 'averagePrice',
            width: '40%',
            render: (text, record) => {
              return <Item >
                {
                  getFieldDecorator(`averagePrice.${record.orderNum}`, {
                    rules: [{
                      pattern: new RegExp(/^[1-9]\d*$/),
                      message: '请输入正整数!'
                    }],
                    /*rules: [{
                        pattern: new RegExp(/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/),
    
                        message: '小数点后最多保留两位小数!'
                      }],*/
                    initialValue: text
                  })
                    (
                      <Input />
                    )
                }
              </Item>
            }
          }
        ];
      }
      //新增表格
      handleAddRow = () => {
        const newData = [
          {
            orderNum: '1',
            projectName: { name: "", num: "" },
            averagePrice: "",
          },
          {
            orderNum: '2',
            projectName: { name: "", num: "" },
            averagePrice: "",
          },
          {
            orderNum: '3',
            projectName: { name: "", num: "" },
            averagePrice: "",
          }
        ]
    
        $state.topThreeDTO = newData
        $state.isDisableFlag1 = true
      }
      render() {
        this.init()
        return (
        //data={{ flag: $state.renderFlag }} 强制渲染表格的一种方法
          <div data={{ flag: $state.renderFlag }}>
            <h1 className='table-title'>
              前三名
              </h1>
            <Button className={$state.isDisableFlag1 ? '' : 'button-in-step'} disabled={$state.isDisableFlag1} onClick={this.handleAddRow}>新增</Button>
            <Table
              className="plain-gray-table"
              dataSource={$state.topThreeDTO}
              columns={this.columns}
              pagination={false}
              bordered
              rowKey={record => record.orderNum}
            />
          </div>
        )
      }
    }
    
    export default Form.create(
      {
        onValuesChange(props, changeValues, allValues) { }
        
      }
    )(ThirdTable)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月21日
  • 已采纳回答 6月13日
  • 创建了问题 6月13日

悬赏问题

  • ¥15 上传图片时提交的存储类型
  • ¥15 Ubuntu开机显示器只显示kernel,是没操作系统(相关搜索:显卡驱动)
  • ¥15 VB.NET如何绘制倾斜的椭圆
  • ¥15 在rhel8中安装qemu-kvm时遇到“cannot initialize crypto:unable to initialize gcrypt“报错”
  • ¥15 arbotix没有/cmd_vel话题
  • ¥15 paddle库安装时报错提示需要安装common、dual等库,安装了上面的库以后还是显示报错未安装,要怎么办呀?
  • ¥20 找能定制Python脚本的
  • ¥15 odoo17的分包重新供应路线如何设置?可从销售订单中实时直接触发采购订单或相关单据
  • ¥15 用C语言怎么判断字符串的输入是否符合设定?
  • ¥15 通信专业本科生论文选这两个哪个方向好研究呀