2015-09-25 185 views
0

我正在做一个关于创建树的反应的教程。 比如这个变量被表示为一棵树:React树 - 如何删除当前节点?

var tree = { 
    title: "howdy", 
    childNodes: [ 
     {title: "bobby"}, 
     {title: "suzie", childNodes: [ 
      {title: "puppy", childNodes: [ 
       {title: "dog house"} 
      ]}, 
      {title: "cherry tree"} 
     ]} 
    ] 
}; 

我想补充旁边它删除当前节点及其子节点每个节点的按钮。

var TreeNode = React.createClass({ 
    getInitialState: function() { 
     return { 
      visible: true 
     }; 
    }, 
    handleDeleteClick: function() { 
     //What should I place here? 
    }, 
    render: function() { 
     console.log(this.state); 
     var childNodes; 
     var classObj; 

     if (this.props.node.childNodes != null) { 
      childNodes = this.props.node.childNodes.map(function(node, index) { 
       return <li key={index}><TreeNode node={node} /></li> 
      }); 

      classObj = { 
       togglable: true, 
       "togglable-down": this.state.visible, 
       "togglable-up": !this.state.visible 
      }; 
     } 

     var style; 
     if (!this.state.visible) { 
      style = {display: "none"}; 
     } 

     return (
      <div> 
       <h5 onClick={this.toggle} className={React.addons.classSet(classObj)}> 
        {this.props.node.title} 

        <span className="input-group-btn"> 
         <button className="btn btn-default" onClick={this.handleDeleteClick}> 
          Delete 
         </button> 
        </span> 
       </h5> 

       <ul style={style}> 
        {childNodes} 
       </ul> 
      </div> 
     ); 
    }, 
    toggle: function() { 
     this.setState({visible: !this.state.visible}); 
    } 
}); 

我该怎么做? 不幸的是,我不能使用数据库作为后端(我可以保持没有数据库的状态吗?)

回答

2

您可能想要将树中的内容不保存在全局变量中,而是保存在组件的状态中。您已经为visible变量使用了该组件的状态,因此请尝试类似地添加tree变量。

要保留您的状态跨越页面重新加载,你可以(现在)使用类似localStorage在那里你可以在每次更改后保存您的树对象(你必须序列化,例如使用JSON.stringify)和当加载它你加载页面(这次使用JSON.parse进行反序列化)。由于您已经很好地抽象了TreeNode组件,因此您应该创建一个新组件(例如Tree),该组件可以:存储树,处理添加/删除节点,处理存储。 Tree组件有一个根节点TreeNode,它通过this.state.tree内容。

var Tree = React.createClass({ 
    getInitialState: function() { 
     return { 
      tree: // ... 
     }; 
    }, 
    handleDeleteClick: function(node) { 
     // do some logic here to remove `node` from whereever it occurs 
     // make sure to COPY this.state.tree and modify that, not modify the 
     // original object, then pass it to this.setState() 
    }, 
    render: function() { 
     return <TreeNode tree={this.state.tree} handleDeleteClick={this.handleDeleteClick} />; 
    } 
}); 

通行证handleDeleteClick下降到每一个树节点上点击链接,你应该调用传下来的回调(this.props.handleDeleteClick),并通过在节点本身或在第一个参数一些标识符(见上面的定义)。