antd  如何传值 ?
发布于 2022-09-12 02:33:32 字数 8789 浏览 34 评论 0

目标:将dataSource2 传入select

复制代码到在线预览直接可运行查看:

在线编辑器地址:(不需要其它配置)
https://codesandbox.io/s/fkc2j


import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Input, Button, Popconfirm, Form,Select } from 'antd';

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
    selectList: [],
    entityNameOptions_kLevelExpand_1: [  //select 临时数据读取
      {
        key: "1",
        value: 1,
        text: "info1"
      },
      {
        key: "2",
        value: 2,
        text: "info2"
      },
      {
        key: "3",
        value: 3,
        text: "info3"
      }
    ],
    entityNameOptions_kLevelExpand_2: [
      {
        key: "4",
        value: 4,
        text: "info4"
      },
      {
        key: "5",
        value: 5,
        text: "info5"
      },
      {
        key: "6",
        value: 6,
        text: "info6"
      }
    ]
  };


  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
        if (dataIndex == "field") {
      return (
        <Form.Item style={{ margin: 0 }}>
          {form.getFieldDecorator(dataIndex, {
            initialValue: "请选择主表字段" //record[dataIndex]
          })(
            <Select
              className="table-user-name-input"
              showSearch
              style={{width:100}}
              placeholder="请选择主表字段"
              optionFilterProp="children"
              onChange={this.onChange}
              onBlur={this.save}
              labelInValue
              filterOption={(input, option) =>
                option.props.children
                  .toLowerCase()
                  .indexOf(input.toLowerCase()) >= 0
              }
            >
              {this.state.entityNameOptions_kLevelExpand_1.map(item => (
                <Option key={item.key} title={item.value}>
                  {item.text}
                </Option>
              ))}
              {/* {connectFormData.mainTableTitle.map(item => (
                <Option key={i++} title={item}>
                  {item}
                </Option>
              ))} */}
            </Select>
          )}
        </Form.Item>
      );
    } else if (dataIndex == "operator") {
      return (
        <Form.Item style={{ margin: 0 }}>
          {form.getFieldDecorator(dataIndex, {
            initialValue: "请选择运算符" //record[dataIndex]
          })(
            <Select
              className="table-user-name-input"
              showSearch
              style={{width:100}}
              placeholder="请选择运算符"
              optionFilterProp="children"
              onChange={this.onChange}
              onBlur={this.save}
              labelInValue
              filterOption={(input, option) =>
                option.props.children
                  .toLowerCase()
                  .indexOf(input.toLowerCase()) >= 0
              }
            >
              <Option value="21">=</Option>
              <Option value="22">></Option>
              <Option value="23">=</Option>
            </Select>
          )}
        </Form.Item>
      );
    } else if (dataIndex == "tablefield") {
      return (
        <Form.Item style={{ margin: 0 }}>
          {form.getFieldDecorator(dataIndex, {
            initialValue: "请选择连接表字段" //record[dataIndex]
          })(
            <Select
              className="table-user-name-input"
              showSearch
              style={{width:100}}
              placeholder="请选择连接表字段"
              optionFilterProp="children"
              onChange={this.onChange}
              onBlur={this.save}
              labelInValue
              filterOption={(input, option) =>
                option.props.children
                  .toLowerCase()
                  .indexOf(input.toLowerCase()) >= 0
              }
            >
              {this.state.entityNameOptions_kLevelExpand_2.map(item => (
                <Option key={item.key} title={item.value}>
                  {item.text}
                </Option>
              ))}
            </Select>
          )}
        </Form.Item>
      );
    }
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: "主表字段",
        dataIndex: "field",
        editable: true
      },
      {
        title: "运算符",
        dataIndex: "operator",
        editable: true
      },
      {
        title: "连接表字段",
        dataIndex: "tablefield",
        editable: true
      },
      {
        title: 'operation',
        dataIndex: 'operation',
        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="Sure to delete?" onConfirm={() => this.handleDelete(record.key)}>
              <a>Delete</a>
            </Popconfirm>
          ) : null,
      },
    ];

    this.state = {
      dataSource: [
        {
          key: '0',
          name: 'Edward King 0',
          age: '32',
          address: 'London, Park Lane no. 0',
        },
        {
          key: '1',
          name: 'Edward King 1',
          age: '32',
          address: 'London, Park Lane no. 1',
        },
      ],
      dataSource2: [  //此数据控制<Table>内容的行数,值无法传入select内
        {
          key: '0',
          name: '1',
          value: '字段名称1'
        },
         {
          key: '1',
          name: '2',
          value: '字段名称2'
        },
      ],
      count: 2,
    };
  }



  handleDelete = key => {
    const dataSource = [...this.state.dataSource];
    this.setState({ dataSource: dataSource.filter(item => item.key !== key) });
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      name: `Edward King ${count}`,
      age: 32,
      address: `London, Park Lane no. ${count}`,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };

  handleSave = row => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData });
  };

  render() {
    const { dataSource,dataSource2 } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <div>
        <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
          Add a row
        </Button>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource2}
          columns={columns}
        />
      </div>
    );
  }
}

ReactDOM.render(<EditableTable />, document.getElementById('container'));
          

如题,这样结构:
antd <Table components={components}/>

这个antdesign结构不常见:
body: {
row: EditableFormRow,
cell: EditableCell
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑕疵 2022-09-19 02:33:32

看到这个问题才之后table才只有有这个属性,我查看了一下它的官方文档。写了一个最简单的例子:antd-table在线查看
这个对象属性的可以修改内部的表格渲染方式,默认情况下行的渲染元素是<tr>,内部单元格用<dt>.table的组件渲染使用了react的组合实现,下面的代码就是我简化后的实现:

const EasyTableHead = ({ ...props }) => {
  return <thead>{props.children}</thead>;
};

const EasyTableHeadRow = ({ ...props }) => {
  return <tr>{props.children}</tr>;
};

const EasyTableHeadCol = ({ ...props }) => {
  return <td>{props.children}</td>;
};

const EasyTable = ({ ...props }) => {
  return (
    <table>
      <EasyTable>
          <EasyTableHead>
              <EasyTableHeadRow>
                  <EasyTableHeadCol>标题 1</EasyTableHeadCol>
                  <EasyTableHeadCol>标题 2</EasyTableHeadCol>
              </EasyTableHeadRow>
          </EasyTableHead>
      </EasyTable>
    </table>
  );
};

对比该组件 components 的 d.ts

export interface TableComponents {

table?: any;

header?: {

wrapper?: any;

row?: any;

cell?: any;

};

body?: {

wrapper?: any;

row?: any;

cell?: any;

};

}

header.row存在时,table内部就将原有的<th>组件替换为该组件,并注入相关的 table 事件。其他的同理

不即不离 2022-09-19 02:33:32

请问这个问题解决了么?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文