diff --git a/components/tree/DirectoryTree.tsx b/components/tree/DirectoryTree.tsx index 7fe32f879b..3dc9b06cff 100644 --- a/components/tree/DirectoryTree.tsx +++ b/components/tree/DirectoryTree.tsx @@ -1,5 +1,6 @@ import * as React from 'react'; import classNames from 'classnames'; +import RcTree from 'rc-tree'; import debounce from 'lodash/debounce'; import { conductExpandParent } from 'rc-tree/lib/util'; import { EventDataNode, DataNode, Key } from 'rc-tree/lib/interface'; @@ -35,18 +36,18 @@ function getTreeData({ treeData, children }: DirectoryTreeProps) { return treeData || convertTreeToData(children); } -const DirectoryTree: React.FC = ({ - defaultExpandAll, - defaultExpandParent, - defaultExpandedKeys, - ...props -}) => { +const DirectoryTree: React.ForwardRefRenderFunction = ( + { defaultExpandAll, defaultExpandParent, defaultExpandedKeys, ...props }, + ref, +) => { // Shift click usage const lastSelectedKey = React.useRef(); const cachedSelectedKeys = React.useRef(); - const ref = React.createRef(); + const treeRef = React.createRef(); + + React.useImperativeHandle(ref, () => treeRef.current!); const getInitExpandedKeys = () => { const { keyEntities } = convertDataToEntities(getTreeData(props)); @@ -93,7 +94,7 @@ const DirectoryTree: React.FC = ({ // Call internal rc-tree expand function // https://github.com/ant-design/ant-design/issues/12567 - ref.current.onNodeExpand(event, node); + treeRef.current!.onNodeExpand(event as any, node); }; const onDebounceExpand = debounce(expandFolderNode, 200, { @@ -220,7 +221,7 @@ const DirectoryTree: React.FC = ({ return ( = ({ ); }; -DirectoryTree.defaultProps = { +const ForwardDirectoryTree = React.forwardRef(DirectoryTree); +ForwardDirectoryTree.displayName = 'DirectoryTree'; + +ForwardDirectoryTree.defaultProps = { showIcon: true, expandAction: 'click' as DirectoryTreeProps['expandAction'], }; -export default DirectoryTree; +export default ForwardDirectoryTree; diff --git a/components/tree/__tests__/directory.test.js b/components/tree/__tests__/directory.test.js index d9bd20df65..56d8f1f02c 100644 --- a/components/tree/__tests__/directory.test.js +++ b/components/tree/__tests__/directory.test.js @@ -250,4 +250,11 @@ describe('Directory Tree', () => { expect.objectContaining({ event: 'select', nativeEvent: expect.anything() }), ); }); + + it('ref support', () => { + const treeRef = React.createRef(); + mount(createTree({ ref: treeRef })); + + expect('scrollTo' in treeRef.current).toBeTruthy(); + }); });