如何使用JavaScript展示我的具有父子关系的数据?

huangapple go评论68阅读模式
英文:

How can I show my data with a parent child relationship with javascript?

问题

Sure, here's the translated code part:

const data = [
    { id: 1, text: 'hello', parent: null },
    { id: 2, text: 'hello2', parent: 1 },
    { id: 3, text: 'hello3', parent: 2 },
    { id: 4, text: 'where are u?', parent: null },
];

function convertToTree(data: any) {
    const tree: any = {};
    data.forEach((item: any) => {
        const parentId = item.parent;
        if (!parentId) {
            tree[item.id] = { ...item, children: [] };
        } else {
            if (!tree[parentId]) {
                tree[parentId] = { children: [] };
            }
            tree[parentId].children.push({ ...item, children: [] });
        }
    });
    return tree;
}

function TreeNode({ data }: any) {
    const [isVisible, setIsVisible] = useState(false);

    const handleClick = () => {
        setIsVisible(!isVisible);
    };

    return (
        <div>
            <p onClick={handleClick}>{data.text}</p>
            {isVisible && data.children && data.children.length > 0 && (
                <ul>
                    {data.children.map((child: any) => (
                        <li key={child.id}>
                            <TreeNode data={child} />
                        </li>
                    ))}
                </ul>
            )}
        </div>
    );
}

I hope this helps you with your JavaScript-React code! If you have any questions or need further assistance, please feel free to ask.

英文:
const data = [
{ id: 1, text: &#39;hello&#39;, parent: null },
{ id: 2, text: &#39;hello2&#39;, parent: 1 },
{ id: 3, text: &#39;hello3&#39;, parent: 2 },
{ id: 4, text: &#39;where are u?&#39;, parent: null },
];
  function convertToTree(data: any) {
const tree: any = {};
data.forEach((item: any) =&gt; {
const parentId = item.parent;
if (!parentId) {
tree[item.id] = { ...item, children: [] };
} else {
if (!tree[parentId]) {
tree[parentId] = { children: [] };
}
tree[parentId].children.push({ ...item, children: [] });
}
});
return tree;
}
function TreeNode({ data }: any) {
const [isVisible, setIsVisible] = useState(false);
const handleClick = () =&gt; {
setIsVisible(!isVisible);
};
return (
&lt;div&gt;
&lt;p onClick={handleClick}&gt;{data.text}&lt;/p&gt;
{isVisible &amp;&amp; data.children &amp;&amp; data.children.length &gt; 0 &amp;&amp; (
&lt;ul&gt;
{data.children.map((child: any) =&gt; (
&lt;li key={child.id}&gt;
&lt;TreeNode data={child} /&gt;
&lt;/li&gt;
))}
&lt;/ul&gt;
)}
&lt;/div&gt;
);
}

I want to show this data as perent-child depending on the parent data in the data using javascript-react.
rule1- when I click on the parent data I want to see the child data.
rule2- since every child can also be a parent, if a child has child data, I want to access its own child data when I click on the child.

But in the code I wrote, only when I click on the parent data, only the children come. As it appears in the data, the child data also has childi, but I cannot see them.

thank you for your help

答案1

得分: 1

这是我现在有的,基本上是将节点递归添加到树中然后打印出来的方法:

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      items: [
        { id: 1, text: 'hello', parent: null },
        { id: 2, text: 'hello2', parent: 1 },
        { id: 3, text: 'hello3', parent: 2 },
        { id: 4, text: 'where are u?', parent: null },
      ]
    }
  }
  
  transformToTree(data) {
    const tree = {};
    
    // 具有父节点但不在树中的元素
    const invisibleParents = {};
    for(let node of data.items) {
      if (!node.parent) {
        // 树的第一个节点
        tree[node.id] = { ...node, children: [] };
        
        if (node.id in invisibleParents) {
          tree[node.id].children.push(...invisibleParents[node.id]);
          delete invisibleParents[node.id];
        }
        
        continue;
      }
      
      if (node.parent in tree) {
        // 直接添加
        tree[node.parent].children.push(node);
      } else {
        if (node.parent in invisibleParents)
          invisibleParents[node.parent].push(node);
        else
          invisibleParents[node.parent] = [node];
      }
    }
    
    return tree;
  }
  
  render() {
    const treeData = this.transformToTree(this.state);
    return (
      treeData.map(x => 
      {
        return (<SmallComponent item={x} />)
      })
    )
  }
}

class SmallComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ...props };
  }
  
  render() {
    const item = this.state.item;
    return (
      <div>
        <p>
          {item.text}
          {item.children.length &&
            <ul>
              <li>
                {item.children.map(x => 
                (
                  <SmallComponent item={x} />
                ))}
              </li>
            </ul>}
        </p>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
英文:

This is what I have, basically your method of recursively adding nodes to the trees and then printing it

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    	items: [
    { id: 1, text: &#39;hello&#39;, parent: null },
    { id: 2, text: &#39;hello2&#39;, parent: 1 },
    { id: 3, text: &#39;hello3&#39;, parent: 2 },
    { id: 4, text: &#39;where are u?&#39;, parent: null },
      ]
    }
  }
  
  transformToTree(data) {
  	const tree = {};
    
    //elems that have a parent but not in tree
    const invisibleParents = {};
    for(let node in data.items)
    {
    	if (!node.parent)
      {
      	//first node of tree
      	tree[node.id] = {...node, children: []};
        
        if (node.id in invisibleParents)
        {
        	tree[node.id].children.push(...invisibleParents[node.id]);
        	delete invisibleParents[node.id];
        }
        
        continue;
      }
      
      if (node.parent in tree)
      {
      	//directly add
        tree[node.parent].children.push(node);
      }
      else
      {
      	if (node.parent in invisibleParents)
        	invisibleParents[node.parent].push(node);
        else
        	invisibleParents[node.parent] = [node];
      }
    }
    
    return tree;
  }
  
  render() {
  const treeData = transformData(this.state.data);
    return (
        treeData.map(x =&gt; 
        {
        	return (&lt;SmallComponent item={x} /&gt;)
        })
    )
  }
}

class SmallComponent extends React.Component
{
  constructor(props)
  {
  	super(props);
    this.state = {...props};
  }
  
	render() {
  item = this.state.item;
  return (
  &lt;div&gt;
  	  &lt;p&gt;
  	    {item.text}
        {item.children.length &amp;&amp; 
        &lt;ul&gt;
          &lt;li&gt;
            {item.children.map(x =&gt; 
            (
            	&lt;SmallComponent item={x} /&gt;
            ))}
          &lt;/li&gt;  
        &lt;/ul&gt;}
  	  &lt;/p&gt;
  	&lt;/div&gt;
    )
  }
}

ReactDOM.render(&lt;TodoApp /&gt;, document.querySelector(&quot;#app&quot;))

huangapple
  • 本文由 发表于 2023年7月4日 20:54:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定