---
title: 外部添加
order: 2
---

本 Demo 演示一行文字的用法。

<!-- prettier-ignore -->
````jsx

import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import ActionTree from '@riil-frontend/component-action-tree';
import { Button, Icon } from '@alifd/next';

const getIconPath = (iconName) => `../demo/images/${iconName}.svg`;

var treeData = [
	{
		id: '0',
		label: '网络设备',
		icon: getIconPath('res_netdevices'),
		count: '1',
		children: [
			{
				id: '0-0',
				parentId: '0',
				label: '锐捷交换机sagggggggggggggggggggggggggggggggggggggggg',
				icon: getIconPath('res_exchanger'),
			},
		],
	},
	{
		id: '1',
		label: '主机',
		icon: getIconPath('res_host'),
	},
];
const loopTree = (data, key, callback) => {
	data.forEach((item, index, arr) => {
		if (item.id === key) {
			return callback(item, index, arr);
		}
		if (item.children) {
			return loopTree(item.children, key, callback);
		}
	});
};

const clone = (data) => JSON.parse(JSON.stringify(data));
function App() {
	const ref = useRef();
	const inputProps = { style: { width: '50px' }, maxLength: 20, defaultValue: '未命名' };
	const [dataSource, setDataSource] = useState(clone(treeData));

	const onExterPositionAdd = (position) => {
		console.log('onExterPositionAdd:', position);
		ref.current.onPositionAdd(position, { type: 'add' });
	};

	const onExterNodeAdd = (parentId) => {
		console.log('onExterNodeAdd:', parentId);
		ref.current.onTreeNodeAdd(parentId, { type: 'add' });
	};

	const onOperation = (node, type) => {
		console.log('onOperation', node, type);
		const { position } = node;
		if (position === 'top') {
			setDataSource([node].concat(dataSource));
			return;
		}
		if (position === 'bottom') {
			setDataSource(dataSource.concat(node));
			return;
		}
		loopTree(dataSource, node.parentId, (parent, index, arr) => {
			parent.children = [{ ...node, id: new Date() + '' }, ...(parent.children || [])];
		});
		setDataSource(clone(dataSource));
	};

	return (
		<div>
			<div style={{ marginBottom: '8px', borderBottom: '#e4e8ed solid 1px' }}>
				<Button type="primary" onClick={() => onExterNodeAdd('1')}>
					在主机下添加
					<Icon type="add"></Icon>
				</Button>
				&nbsp;&nbsp;
				<Button type="primary" onClick={() => onExterPositionAdd('top')}>
					在顶部添加
					<Icon type="add"></Icon>
				</Button>
				&nbsp;&nbsp;
				<Button type="primary" onClick={() => onExterPositionAdd('bottom')}>
					在底部添加
					<Icon type="add"></Icon>
				</Button>
				<br />
				<br />
			</div>
			<ActionTree ref={ref} draggable={false} dataSource={dataSource} onOperation={onOperation} inputProps={inputProps} />
		</div>
	);
}

ReactDOM.render(<App />, mountNode);


````
