2017-07-25 154 views
1

我目前正在开发中ReactJS自定义组件,可以根据JSON显示树:传递数据反应组件动态

export default { 
    name: 'Main Node', nodeid: 99,toggled: true, 
    children: [ 
     { name: 'Secondary Node',nodeid: 0, 
      chosen: false,pushed: false,toggled: false, 
      children: [ 
       { name: 'Leaf Node',nodeid: 1,chosen: false, 
        pushed: false, toggled: false, 
        children: [{ 
        name : "child 1", pushed: false, 
        toggled: false, chosen:false 
        }] 
       } 
      ] 
     } 
    ] 
}; 

React Hierarchical Tree 目前,该组件能够呈现自己,因为我我从静态Data.js文件发送JSON,如下图所示:

import React from 'react'; 
import TreeComponent from 'reusable-components/TreeComponent'; 
import HierarchyJson from './internal/Data'; 

export default function ExampleTreeComponent() { 
    return <TreeComponent hierarchyJson={HierarchyJson} functionMode={4} htmlId="tree1" 
    pushLabelValue="include SubLevel" 
    unpushAlertText="plz choose something" 
    pushAlertText="plz choose something" /> 
} 

我想实现的是我的网页中具有相同的功能,但是从HTTP调用接收JSON数据。

我是ReactJS的初学者,所以我迷失了。

+0

您可以简单地将http调用的响应作为prop,即hierarchyJson传递,就像传递静态数据一样。它会工作。 –

+0

我在做HTTP调用时遇到了麻烦,因为我的应用程序是一个struts/jsp应用程序。 我可以通过jquery post进行调用,然后从js块内传递该回报作为道具吗? 另外...我不能让构建文件在IE上正常工作,他们一直说TreeComponent是无效的。 –

回答

0

你的树组件不需要担心数据来自哪里,而只是担心有数据。换句话说,无论是从某个本地文件还是从ajax请求到api的数据都不应该成为树组件的关注点。所有你需要的是确保它所需的数据被发送到它。这是我的意思的一个例子。

class sample extends React.Component { 
    constructor() { 
     this.state = { 
      myData: {} //this is the tree 
     } 
    } 

    componentDidMount() { 
     ajax.request(some end point).then(data => { 
      this.setState({myData: data}); 
     }) 
     //this is where its recomended to make async calls. When the promise resolves 
     //the component will render again due to setState being called 
     //and this time myData will be your data from the api 
     //and now the tree component has what it needs to render the data 
    } 

    render() { 
     <Tree data={myData} /> // 
    } 
} 
+0

如何将HTTP调用传递给组件,以便它知道从哪里检索数据?我的组件将在应用程序的某些部分重用,因此端点调用需要可配置。 –