You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.3 KiB

---
order: 1
title:
zh-CN: 受控操作示例
en-US: Controlled Tree
---
9 years ago
## zh-CN
9 years ago
受控操作示例
## en-US
Controlled mode lets parent nodes reflect the status of child nodes more intelligently.
```tsx
import React, { useState } from 'react';
9 years ago
import { Tree } from 'antd';
const treeData = [
{
title: '0-0',
key: '0-0',
7 years ago
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{ title: '0-0-0-0', key: '0-0-0-0' },
{ title: '0-0-0-1', key: '0-0-0-1' },
{ title: '0-0-0-2', key: '0-0-0-2' },
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{ title: '0-0-1-0', key: '0-0-1-0' },
{ title: '0-0-1-1', key: '0-0-1-1' },
{ title: '0-0-1-2', key: '0-0-1-2' },
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
7 years ago
children: [
{ title: '0-1-0-0', key: '0-1-0-0' },
{ title: '0-1-0-1', key: '0-1-0-1' },
{ title: '0-1-0-2', key: '0-1-0-2' },
],
},
{
title: '0-2',
key: '0-2',
},
];
9 years ago
const Demo = () => {
const [expandedKeys, setExpandedKeys] = useState<string[]>(['0-0-0', '0-0-1']);
const [checkedKeys, setCheckedKeys] = useState<string[]>(['0-0-0']);
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
const onExpand = expandedKeys => {
console.log('onExpand', expandedKeys);
// if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
setExpandedKeys(expandedKeys);
setAutoExpandParent(false);
};
const onCheck = checkedKeys => {
console.log('onCheck', checkedKeys);
setCheckedKeys(checkedKeys);
};
const onSelect = (selectedKeys, info) => {
9 years ago
console.log('onSelect', info);
setSelectedKeys(selectedKeys);
};
return (
<Tree
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onCheck}
checkedKeys={checkedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={treeData}
/>
);
};
9 years ago
ReactDOM.render(<Demo />, mountNode);
```