frontend9 / fe9-library

九部知识库
1.94k stars 138 forks source link

自定义表单控件之可选择的表格 #55

Open dengfuping opened 6 years ago

dengfuping commented 6 years ago

实现原理

undefined

初始化项目

$ mkdir demo-form-table && cd demo-form-table
$ yarn create umi

undefined

编写 FormTable 组件

import React from 'react';
import { Table } from 'antd';

class FormTable extends React.Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (
      <Table { ...this.props }/>
    );
  }
}

export default FormTable;
render() {
  const { selectedRowKeys } = this.state;
  const rowSelection = {
    selectedRowKeys,
    onChange: this.handleSelectChange,
  };
  const newProps = {
    ...this.props,
    rowSelection,
  }
  return (
    <Table {...newProps} />
  );
}
handleSelectChange = selectedRowKeys => {
  const { onChange } = this.props;
  if (onChange) {
    onChange(selectedRowKeys);
  }
};
static getDerivedStateFromProps(props) {
  const newState = {
    prevProps: props,
  };
  const { value } = props;
  if ('value' in props) {
    // 将下发的 value 赋值给 FormTable,这里将 selectedRowKeys 作为 FormTable 的值
    newState.selectedRowKeys = value;
  }
  return newState;
}

测试一下

import React from 'react';
import { Form } from 'antd';
import FormTable from '../components/FormTable';
import styles from './index.css';

const FormItem = Form.Item;

class IndexPage extends React.Component {
  render() {
    const { form: { getFieldDecorator, getFieldValue } } = this.props;
    const columns = [{
      title: 'Name',
      dataIndex: 'name',
      render: text => <a href="javascript:;">{text}</a>,
    }, {
      title: 'Age',
      dataIndex: 'age',
    }, {
      title: 'Address',
      dataIndex: 'address',
    }];
    const dataSource = [{
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New York No. 1 Lake Park',
    }, {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park',
    }, {
      key: '3',
      name: 'Joe Black',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
    }, {
      key: '4',
      name: 'Disabled User',
      age: 99,
      address: 'Sidney No. 1 Lake Park',
    }];
    return (
      <div className={styles.container}>
        <Form>
          <FormItem label="表格表单项">
            {
              getFieldDecorator('selectedRowKeys', {})(<FormTable dataSource={dataSource} columns={columns} />)
            }
          </FormItem>
        </Form>
        <h4>选中项为: {getFieldValue('selectedRowKeys') && getFieldValue('selectedRowKeys').join(', ')}</h4>
      </div>
    );
  }
}

export default Form.create()(IndexPage);

undefined

yesmeck commented 6 years ago

FormTable 只作为一个受控组件来说的话,selectedRowKeys 这个状态是多余的,直接用 this.props.selectedRowKeys 就可以了。