学无先后,达者为师

网站首页 编程语言 正文

将antd中的Tree组件放在Form表单里面

作者:小五Ivy 更新时间: 2022-02-24 编程语言

问题:

  • 前一段时间使用antd的Tree组件的时候遇到一个问题:将Tree组件放在Form表单的时候,想用initialValueTreedefaultExpandedKeys,defaultSelectedKeys和defaultCheckedKeys赋初始值,已找到解决方法。

解决思路:

  • Tree 不是 form control,你不能直接把 Tree 丢给 getFieldDecorator,需要把 Tree 封装下再丢给 getFieldDecorator
  • 注意4.x版本的antd不支持Form.create()()方法。

代码展示

1. 封装Tree
export default  class TreeDemo extends React.Component {
  render() {
    return (
      <Tree
        checkable
        expandedKeys={['STATUS']}
        checkedKeys={this.props.value}
        onCheck={this.props.onChange}
      >
        <TreeNode title="全选" key="STATUS">
          <TreeNode title="未成交" key="A"></TreeNode>
          <TreeNode title="已成交" key="B"></TreeNode>
          <TreeNode title="流拍" key="C"></TreeNode>
          <TreeNode title="未来供应" key="D"></TreeNode>
        </TreeNode>
      </Tree>
    );
  }
}

2. Form表单

import React from 'react';
import { toJS } from 'mobx';
import { observer } from "mobx-react";
import { Row, Col, Button, Form, Popconfirm, message, Checkbox, Tree } from 'antd';

const { Item } = Form
const { TreeNode } = Tree;

class Index extends React.Component {
  constructor(props) {
    super(props)
    this.state = {checkList:['A']}
  }

  //确定
  handleSubmit = e => {
    e && e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(toJS(values));

      if (!err) {
        //验证无误
        console.log('验证无误---');
        this.props.state.getParcelList()
      }
    });
  }

  //土地状态
  onCheck = checkedKeys => {
    //过滤掉父级的key
    checkedKeys = checkedKeys.filter(item => item !== 'STATUS')
    this.setState({checkList:checkedKeys})
  };

  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <div>
        <Form layout="inline" autoComplete="off" onSubmit={this.handleSubmit} >      
          <Row>
            <Col span={4}>demo</Col>
            <Col span={20}>
              <Item>
                {
                  getFieldDecorator('demo', {
                    initialValue: this.state.checkList,
                  })
                    (
                      <TreeDemo onChange={this.onCheck} />
                    )}
              </Item>
            </Col>
          </Row>        
          <Row type='flex' justify="center">
            <Button type='primary' htmlType="submit">确定</Button>
          </Row>
        </Form>
      </div>
    )
  }
}
export default Form.create({
  onValuesChange(props, changeValues, allValues) {
    // console.log(allValues, 'allValues');

  }
})(Index);

原文链接:https://blog.csdn.net/weixin_44471622/article/details/106994055

栏目分类
最近更新