背景:
基於項目需要,在搜索第三方類庫后沒有很好的效果后決定動手實現。
開發環境:
React Native 0.44
模型:
由於數據已經全部取出,不需要分級異步加載,故而只需要實現層級展示即可。
設計:
從以上模型可以分布解析:
首先輸入部分需要規划需要哪些東西輸入,最基本的可以確定是源數據(data),另外根據初始化的狀態,我們還可以確定需要在展示時,節點是否被選中(selectedItems)或者是否是展開關閉等等。
因此可以定義組件屬性如下:
1 export default class TreeView extends Component { 2 static propTypes = { 3 data: PropTypes.array, 4 selectedItems: PropTypes.array, 5 }; 6
7 static defaultProps = { 8 data: [], 9 selectedItems: [], 10 }; 11 }
組件處理部分,需要提供對外的接口回調處理,包括一些狀態的改變、事件的處理等等:
基於此,可以擴展默認屬性定義(默認主鍵采用UUID生成):
static propTypes = { data: PropTypes.array, selectedItems: PropTypes.array, onItemClick: PropTypes.func, onItemSelect: PropTypes.func, onItemExpand: PropTypes.func, onGetItemDisplayText: PropTypes.func, onGetItemKey: PropTypes.func, onGetSubList: PropTypes.func, collapsableComponent: PropTypes.func, itemComponent: PropTypes.func, }; static defaultProps = { data: [], selectedItems: [], onItemClick: (levelIndex, index, item) => { }, onItemSelect: (checked, item) => { }, onItemExpand: (levelIndex, index, item) => { }, onGetItemDisplayText: (item) => { return item; }, onGetSubList: (item) => { return item.list || []; }, onGetItemKey: (item) => { return uuidv4(); }, collapsableComponent: (item, open, hasSubList) => { if (!hasSubList) { return (<Text>{}</Text>); } return (<Text>{open ? '-' : '+'}</Text>); }, itemComponent: (item) => { return (<Text style={{flex: 1, marginHorizontal: 10,}}>{item.text}</Text>); }, };
綜合上述兩步鋪墊之后,剩下的展示工作就比較好辦了。