How to manage state in a tree component in reactjs

后端 未结 3 798
孤城傲影
孤城傲影 2021-02-02 14:37

I\'ve been struggling this for a couple of days, trying to figure out the \"react\" way to do it.

Basically, I have a tree, a list of lists (of lists ...) that can be ar

相关标签:
3条回答
  • 2021-02-02 15:14

    I wanted to try out the tree structure with React and came up with a simple component that hides subtrees when you click on <h5>. Everything is a TreeNode. Is this similar to what you were thinking?

    You can see it in action in this JSFiddle: http://jsfiddle.net/ssorallen/XX8mw/

    TreeNode.jsx:

    var TreeNode = React.createClass({
      getInitialState: function() {
        return {
          visible: true
        };
      },
      render: function() {
        var childNodes;
        if (this.props.node.childNodes != null) {
          childNodes = this.props.node.childNodes.map(function(node, index) {
            return <li key={index}><TreeNode node={node} /></li>
          });
        }
    
        var style = {};
        if (!this.state.visible) {
          style.display = "none";
        }
    
        return (
          <div>
            <h5 onClick={this.toggle}>
              {this.props.node.title}
            </h5>
            <ul style={style}>
              {childNodes}
            </ul>
          </div>
        );
      },
      toggle: function() {
        this.setState({visible: !this.state.visible});
      }
    });
    

    bootstrap.jsx:

    var tree = {
      title: "howdy",
      childNodes: [
        {title: "bobby"},
        {title: "suzie", childNodes: [
          {title: "puppy", childNodes: [
            {title: "dog house"}
          ]},
          {title: "cherry tree"}
        ]}
      ]
    };
    
    React.render(
      <TreeNode node={tree} />,
      document.getElementById("tree")
    );
    
    0 讨论(0)
  • 2021-02-02 15:24

    Here is a quick example of how to create a treeview using React and Flux. http://www.syntaxsuccess.com/viewarticle/5510d81be1ce52d00e93da55

    The React component is recursive and state is managed using Flux.

    0 讨论(0)
  • 2021-02-02 15:25

    Seems like it'd be nicer to pass everything down as props, as this will prevent you from the trouble of managing individual insertion/deletion. Also, like the comments said, the key attributes prevents a huge chunk of unnecessary re-rendering.

    You might want to check this link: http://facebook.github.io/react/blog/2013/11/05/thinking-in-react.html. It describes the kind of dilemma you're having and how to approach it.

    (Coincidentally, I've made a react tree view a while ago: https://github.com/chenglou/react-treeview. Take whatever you want from it!)

    0 讨论(0)
提交回复
热议问题