我尝试从语义UI反应基于列表创建TreeView。 我在展开树上有问题。我使用onClick触发扩展。所有这些都适用于根项目,但不适用于子树元素。看起来,鼠标单击子项也会触发父项的相同事件。
当我单击项目5时,我在控制台中看到: 点击了ID = 5的项目 ListExampleTree用鼠标收到点击 点击ID为2的商品 ListExampleTree收到了鼠标单击
我做错了什么?
您可以通过链接-https://codesandbox.io/s/oq3wlxr5p5
在下面找到我的课程或正在运行的代码段
import React, { Component } from "react";
import { List, Icon } from "semantic-ui-react";
class TreeNode extends Component {
constructor(props) {
super(props);
this.state = {
node: props.node,
expanded: false
};
}
componentDidMount() {
this.setState({
node: this.props.node,
expanded: this.props.expanded
});
}
onItemClick = (value) => {
console.log('Clicked on item with id=' + value)
this.setState({
expanded: !this.state.expanded
});
this.props.onItemClick(value);
};
renderChildItems() {
let { node } = this.state;
if (!Array.isArray(node.childNodes) || !node.childNodes.length) {
return <div />;
}
let nodesList = node.childNodes.map(node => {
return (
<TreeNode
key={node.id}
node={node}
onItemClick={this.props.onItemClick}
/>
);
});
return <List.List>{nodesList}</List.List>;
}
render() {
let { node } = this.state;
let icon = "triangle right";
let childNodes = [];
if (this.state.expanded) {
icon = "triangle down";
childNodes = this.renderChildItems();
}
return (
<List.Item key={node.id} value={node.id} onClick={(event) => this.onItemClick(node.id)}>
<Icon name={icon} />
<List.Content>
<List.Header>{node.text}</List.Header>
<List.Description>{node.text}</List.Description>
{childNodes}
</List.Content>
</List.Item>
);
}
}
let second3LevelNodes = [
{
id: "6",
text: "item 6",
childNodes: []
},
{
id: "7",
text: "item 7",
childNodes: []
}
];
let secondLevelNodes = [
{
id: "4",
text: "item 4",
childNodes: []
},
{
id: "5",
text: "item 5",
childNodes: second3LevelNodes
}
];
let firstLevelNodes = [
{
id: "1",
text: "item 1",
childNodes: []
},
{
id: "2",
text: "item 2",
childNodes: secondLevelNodes
},
{
id: "3",
text: "item 3",
childNodes: []
}
];
class ListExampleTree extends Component {
onItemClick = (value) => {
console.log("ListExampleTree received click with mouse");
};
render() {
let nodes = firstLevelNodes;
if (!Array.isArray(nodes) || !nodes.length) {
return (
<div>
<p>empty</p>
</div>
);
}
console.log(nodes);
return (
<List>
{nodes.map(node => {
return (
<TreeNode
key={node.id}
node={node}
onItemClick={this.onItemClick}
/>
);
})}
</List>
);
}
}
export default ListExampleTree;