Code Monkey home page Code Monkey logo

tree's Introduction

rc-tree

Tree component.

NPM version dumi build status Test coverage Dependencies DevDependencies npm download bundle size

Screenshots

Feature

  • Support all popular browsers, including Internet Explorer 9 and above.

Example

http://localhost:9001/

online example: https://tree.react-component.now.sh/

Install

rc-tree

Usage

Note: import "rc-tree/assets/index.css"

see examples

API

Tree props

name description type default
autoExpandParent whether auto expand parent treeNodes bool false
checkable whether support checked bool/React Node false
checkedKeys Controlled checked treeNodes(After setting, defaultCheckedKeys will not work). Note: parent and children nodes are associated, if the parent node's key exists, it all children node will be checked, and vice versa. When set checkable and checkStrictly, it should be an object, which contains checked array and halfChecked array. String[]/{checked:Array,halfChecked:Array} []
checkStrictly check node precisely, parent and children nodes are not associated bool false
className additional css class of root dom node String ''
defaultCheckedKeys default checked treeNodes String[] []
defaultExpandedKeys expand specific treeNodes String[] []
defaultExpandAll expand all treeNodes bool false
defaultExpandParent auto expand parent treeNodes when init bool true
defaultSelectedKeys default selected treeNodes String[] []
disabled whether disabled the tree bool false
draggable whether can drag treeNode. (drag events are not supported in Internet Explorer 8 and earlier versions or Safari 5.1 and earlier versions.) bool | ({ node }) => boolean false
expandedKeys Controlled expand specific treeNodes String[] -
filterTreeNode filter some treeNodes as you need. it should return true function(node) -
icon customize icon. When you pass component, whose render will receive full TreeNode props as component props element/Function(props) -
loadedKeys Mark node is loaded when loadData is true String[] -
loadData load data asynchronously and the return value should be a promise function(node) -
multiple whether multiple select bool false
prefixCls prefix class String 'rc-tree'
selectable whether can be selected bool true
selectedKeys Controlled selected treeNodes(After setting, defaultSelectedKeys will not work) String[] []
showIcon whether show icon bool true
showLine whether show line bool false
treeData treeNodes data Array, if set it then you need not to construct children TreeNode. (value should be unique across the whole array) array<{key,title,children, [disabled, selectable]}> -
onCheck click the treeNode/checkbox to fire function(checkedKeys, e:{checked: bool, checkedNodes, node, event, nativeEvent}) -
onExpand fire on treeNode expand or not function(expandedKeys, {expanded: bool, node, nativeEvent}) -
onDragEnd it execs when fire the tree's dragend event function({event,node}) -
onDragEnter it execs when fire the tree's dragenter event function({event,node,expandedKeys}) -
onDragLeave it execs when fire the tree's dragleave event function({event,node}) -
onDragOver it execs when fire the tree's dragover event function({event,node}) -
onDragStart it execs when fire the tree's dragstart event function({event,node}) -
onDrop it execs when fire the tree's drop event function({event, node, dragNode, dragNodesKeys}) -
onLoad Trigger when a node is loaded. If you set the loadedKeys, you must handle onLoad to avoid infinity loop function(loadedKeys, {event, node}) -
onMouseEnter call when mouse enter a treeNode function({event,node}) -
onMouseLeave call when mouse leave a treeNode function({event,node}) -
onRightClick select current treeNode and show customized contextmenu function({event,node}) -
onSelect click the treeNode to fire function(selectedKeys, e:{selected: bool, selectedNodes, node, event, nativeEvent}) -
switcherIcon specific the switcher icon. ReactNode / (props: TreeNodeAttribute) => ReactNode -
virtual Disable virtual scroll when false boolean -
allowDrop Whether to allow drop on node ({ dragNode, dropNode, dropPosition }) => boolean -
dropIndicatorRender The indicator to render when dragging ({ dropPosition, dropLevelOffset, indent: number, prefixCls }) => ReactNode -
direction Display direction of the tree, it may affect dragging behavior ltr | rtl -
expandAction Tree open logic, optional: false | click | doubleClick string | boolean click

TreeNode props

note: if you have a lot of TreeNode, like more than 1000,
make the parent node is collapsed by default, will obvious effect, very fast.
Because the children hide TreeNode will not insert into dom.

name description type default
className additional class to treeNode String ''
checkable control node checkable if Tree is checkable bool false
style set style to treeNode Object ''
disabled whether disabled the treeNode bool false
disableCheckbox whether disable the treeNode' checkbox bool false
title tree/subTree's title String/element/((data: DataNode) => React.ReactNode) '---'
key it's used with tree props's (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys. you'd better to set it, and it must be unique in the tree's all treeNodes String treeNode's position
isLeaf whether it's leaf node bool false
icon customize icon. When you pass component, whose render will receive full TreeNode props as component props element/Function(props) -
switcherIcon specific the switcher icon. ReactNode / (props: TreeNodeAttribute) => ReactNode -

Note

The number of treeNodes can be very large, but when enable checkable, it will spend more computing time, so we cached some calculations(e.g. this.treeNodesStates), to avoid double computing. But, this bring some restrictions, when you async load treeNodes, you should render tree like this {this.state.treeData.length ? <Tree ...>{this.state.treeData.map(t => <TreeNode ... />)}</Tree> : 'loading tree'}

Development

npm install
npm start

Test Case

http://localhost:8018/tests/runner.html?coverage

Coverage

http://localhost:8018/node_modules/rc-server/node_modules/node-jscover/lib/front-end/jscoverage.html?w=http://localhost:8018/tests/runner.html?coverage

License

rc-tree is released under the MIT license.

Other tree views

tree's People

Contributors

07akioni avatar addictional avatar afc163 avatar benjycui avatar berber1016 avatar chenshuai2144 avatar coldice8 avatar curly210102 avatar daoxinghuang avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar evgeniya-osmakova avatar ex90rts avatar fireairforce avatar gleancoder1116 avatar jljouannic avatar katdivyareddy10 avatar li-jia-nan avatar madccc avatar ne-smalltown avatar tubs-coder avatar twisger avatar valleykid avatar warmhug avatar yesmeck avatar yiminghe avatar yoyo837 avatar yuiai01 avatar zombiej avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tree's Issues

[feature request] Dynamic context menu to elements in the tree

Would like to have the possibility on right-click (context-menu) to display possible actions related to the actual node. Callback to a function to get the right context-menu items and identifiers, or as a parameter to the TreeNode construction. Selected action would have to have function callback like onSelect.

Right click would have to select the node, and display the context-menu. Possible? :-)

Dynamic render example with 8 levels or greater not working

If you modify the dynamic render example to have 8 levels or greater, and you try to select all children from the root node, the UI does not check all children nodes.

To reproduce the issue:

  1. Copy the code from the dynamic example:
    http://react-component.github.io/tree/examples/dynamic.html

  2. Create 8 levels of tree nodes:
    Update line 84 from
    getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2);
    to
    getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 8);

  3. Run the code, and expand 8 levels all of the pNode 02 children.

  4. Check pNode 02 at the root level.

  5. You would expect to see of all pNode 02's children checked, however, the root node remained unchecked, as do the children on levels 1-7. The leaf on level 8 is checked.

Also, it appears the checked keys is showing the correct value, even though the UI is not reflecting all of the checked key values.

github_bug1

Trigger expand

Hi, is it possible to trigger the expansion of the nodes in my code, given an eventKey?

onCheck逻辑中的冗余

一个节点选中的时候 应该是只会影响自己的父节点和子节点 是不是没有必要遍历所有已选中的状态进行handleCheckState?

不能在TreeNode 上面添加自己的 组件

比如我想为一个treeNode 添加一个删除的icon, 现在只能通过title 的方式修改内容
建议

  1. title 模式 改为 TreeNode 添加自定义 children
  2. title 可以以html 的方式 set

Uncaught TypeError: Cannot read property 'then' of undefined

when I expanded a node every time,it will trigger this error.

      // after data loaded, need set new expandedKeys
      if (expand && this.props.loadData) {
        return this.props.loadData(treeNode).then(function () {
          if (!controlled) {
            _this2.setState({ expandedKeys: expandedKeys });
          }
        });
      }
onExpand    @   Tree.js?e208:211
onExpand    @   TreeNode.js?82a7:149
ReactErrorUtils.invokeGuardedCallback   @   ReactErrorUtils.js?6b31:71
executeDispatch @   EventPluginUtils.js?0958:79
executeDispatchesInOrder    @   EventPluginUtils.js?0958:102
executeDispatchesAndRelease @   EventPluginHub.js?c6b1:43
executeDispatchesAndReleaseTopLevel @   EventPluginHub.js?c6b1:54
forEachAccumulated  @   forEachAccumulated.js?b898:23
processEventQueue   @   EventPluginHub.js?c6b1:259
runEventQueueInBatch    @   ReactEventEmitterMixin.js?8a20:18
handleTopLevel  @   ReactEventEmitterMixin.js?8a20:34
handleTopLevelWithoutPath   @   ReactEventListener.js?2365:93
handleTopLevelImpl  @   ReactEventListener.js?2365:73
perform @   Transaction.js?6dff:136
batchedUpdates  @   ReactDefaultBatchingStrategy.js?ef70:62
batchedUpdates  @   ReactUpdates.js?ce09:94
dispatchEvent   @   ReactEventListener.js?2365:204

how to change icon

hi author ! i see default icon is a folder, so how can i change to another one ?

get pos in TreeNode title

Hello, I have a custom title including a dropdown select. I want to get the pos or key of the TreeNode to make the select onChange call. How can I get it? Thanks.

rc-tree does not ship with the image assets it requires

Hi,

I've just noticed that the assets for rc-tree are not included with the component; instead they are links to a website called t.alipayobjects.com:

I can work around this locally by manually downloading the assets and monkey-patching the css.

However, it might be better for users of rc-tree that don't know they need to do this that the assets were included as part of the project. It should just be a case of including them alongside the css.

Do you have any thoughts about doing that?

Style bug

The height value set by selector .rc-tree li .rc-tree-node-content-wrapper is causing style problem. Please remove it.
screenshot

Cannot set property of 'checked' of undefined

I need to be able to track which keys are checked on the tree so I can render a new tree with those keys already selected. From what I can tell, the 'checked' property it is looking for only applies if the "checkedStrictly" property it true. When the component loads up and I try to check any node, I get the following error:

"Tree.js:208:253 Uncaught TypeError: Cannot set property 'checked' of undefined"

My component is below:

import React, {PropTypes} from 'react';
import Tree, { TreeNode } from 'rc-tree';

const SearchResultsTree = ({data, loading, onCheckProposal, checkedKeys
  }) => {

/* eslint-disable react/no-multi-comp */
  const loop = (treeData) => {
    return treeData.map((item) => {
      if (item.opportunities) {
        return (
          <TreeNode
            key={'client ' + item.id} title={item.title}
          >
            {loop(item.opportunities)}
          </TreeNode>
        );
      }
      else if (item.proposals) {
        return (
         <TreeNode
            key={'opportunity ' + item.id} title={item.title}
          >
            {loop(item.proposals)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.proposalId} title={item.proposalName} />;
    });
  };
/* eslint-enablereact/no-multi-comp */

  console.log(checkedKeys);
  return (
    <fieldset className="search-results">
      <legend><h5>Search Results</h5></legend>
      <div className="results-tree">
        {loading ?
          <p>
            Loading...
          </p>
          :
          <Tree
            checkable
            autoExpandParent={false}
            selectable={false}
            onCheck={onCheckProposal}
            checkedKeys={checkedKeys}
          >
            {loop(data)}
          </Tree>

        }
      </div>
    </fieldset>
  );
};

SearchResultsTree.propTypes = {
  data: PropTypes.array,
  loading: PropTypes.bool,
  onCheckProposal: PropTypes.func.isRequired,
  checkedKeys: PropTypes.array
};

export default SearchResultsTree;

make TreeNode non-selectable

I have a tree with nodes that I can select, but nodes have attributes and user should not be able to select them. Is it possible to set select={false} per TreeNode?

Thanks Alex

Hide checkbox on specific TreeNode (or to have it only for the leaf ones)

Is it possible to obtain a tree like this?
image
Basically I want to have the checkbox only when isLeaf={true}
I know i can disable it on those treenodes, but I want to hide it also or better to Remove it so it will not appear in the checkedKeys.

Please le me know if I'm wrong opening this issue and if there are other channels for this kind of questions.
Thanks ahead of time!

Get started tutorial

Hi,
is there any example for using this control?
Also does it support ~100K nodes? ~25K nodes on the same level?

Thanks,
Jonathan

how to change the icon for the node

i passed icon attribute with image path as props to treeNode but the image is not displaying in the tree.

can you suggest how to add the custom icon for node in the tree

hao to use rc-tree with other module in webpack?

while i use rc-tree with other modules (such as react-fluxbox-grid ),i should make webpack as this :

{
        test: /(\.scss|\.css)$/,
        loaders: ['style', 'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass?sourceMap']
      }

then ,my rc-tree can not display checkbox and can not choose checkbox......

util.js: Cannot read property 'file' of undefined

我把rc-tree组件的源码拿出来,单独放在项目内使用。可是在webpack中报这个错误。
具体是在handleCheckState()函数的代码导致的错误。因为我把这个函数注释掉后,就不再报错了。

WARNING in ./static/component/outline/outline/tree/util.js
Module build failed: TypeError: F:/jinrunsen/Projects/fansmanage/static/component/outline/outline/tree/util.js: Cannot read property 'file' of undefined
    at Plugin.buildExpressionHandler (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-plugin-import\1.0.1\babel-plugin-import\lib\Plugin.js:49:26)
    at Plugin.ExpressionStatement (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-plugin-import\1.0.1\babel-plugin-import\lib\Plugin.js:204:14)
    at applyInstance (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-plugin-import\1.0.1\babel-plugin-import\lib\index.js:27:26)
    at PluginPass.ret.visitor.(anonymous function) (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-plugin-import\1.0.1\babel-plugin-import\lib\index.js:85:9)
    at newFn (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\visitors.js:276:21)
    at NodePath._call (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\path\context.js:76:18)
    at NodePath.call (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\path\context.js:48:17)
    at NodePath.visit (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\path\context.js:105:12)
    at TraversalContext.visitQueue (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\context.js:150:16)
    at TraversalContext.visitMultiple (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\context.js:103:17)
    at TraversalContext.visit (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\context.js:190:19)
    at Function.traverse.node (F:\jinrunsen\Projects\fansmanage\node_modules\.npminstall\babel-traverse\6.18.0\babel-traverse\lib\index.js:114:17)
 @ ./static/component ^\.\/.*$

Get root parent node in onSelect method

I have made a tree with several layers of nesting. The onSelect property is on <Tree>, so I have to handle selection for any node in the same method. If I have selected a <TreeNode> that is several levels deep, I'd like to know the parent node at the root level from within the onSelect method. The parameters passed to this method are:

function(selectedKeys, e:{selected: bool, selectedNodes, node, event})

While inspecting the contents of e in the browser debugger, I was not able to find an immediate (or otherwise) way to access the parent node at the root level, or parent nodes in general. How can I do this? Thanks in advance.

onExpand

When is the onExpand fired? because somehow i don't see the console.log of the expand, i see the start, enter and drop events, but not the onExtand?

the tree is getting expanded, looks like the events just not fired.

Component Spec

功能

  • 支持多选,单选
  • 支持键盘操作

使用示例

var tree = <Tree defaultCheckedKeys={['1','2-1']}>
<TreeNode title="1"  key='1'/>
<TreeNode title='2' key='2'>
<TreeNode title='2-1' key='2-1' />
</TreeNode>
</Tree>

API

Tree

name type default description
className String 多余的根部样式
prefixCls String rc-tree 前缀样式
showLine Boolean false 是否显示连接线
checkable Boolean false 是否允许多选
checkedKeys String[] [] 当前选中的节点
defaultCheckedKeys String[] [] 初始选中的节点
defaultExpandedKeys String[] [] 初始展开的节点
onCheck function({checked,node,key}) 选中一个节点时调用

TreeNode

name type default description
className String 节点的多余样式
disabled Boolean false 是否禁用
key Object 用于 selectedKeys 指定选中节点
title React Element 节点的显示内容
children TreeNode[] 子节点

参考

有问题

node_modules/rc-tree/lib/TreeNode.js:39
[0] var browserUa = (0, _util.browser)(window.navigator.userAgent || '');
[0] ^
[0]
[0] ReferenceError: window is not defined

Performance issues when toggling the checkbox of a parent node with 100s of child/grandchild nodes

When toggling the checkbox of a parent node with 100s of child/grandchild nodes, it can take several seconds (usually 2-3 seconds) before the result is rendered, which is not a good user experience.

Would it be possible for you to improve the performance of this operation?

More info: I am using the "checkedKeys" parameter for <Tree>, and I'm specifying only leaf nodes (ie. nodes with no children) in that parameter (as this makes my application logic much simpler).

need to do

性能问题(大量数据下)

  • 分页/分步渲染,不再一次插入所有数据

主要的“功能/demo”缺失

其他

  • 点击title、使节点展开/收起;展开当前节点时、相邻已展开节点收起(作为菜单)
  • 支持键盘操作

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.