问题:
前一段时间使用antd的Tree组件的时候遇到一个问题:将Tree
组件放在Form
表单的时候,想用initialValue
给Tree
的defaultExpandedKeys,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 => {
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) {
}
} ) ( Index) ;