我开始使用React,我想在我的项目中添加一个react-tree组件。 我试图删除函数removeNode()中的节点:
removeNode(e){
this.setState({
treeData: removeNodeAtPath({
treeData: this.state.treeData,
path: ????,
getNodeKey: ({node: TreeNode, treeIndex: number}) => {
console.log(number);
return number;
},
ignoreCollapsed: false,
})
})
}
如何在我的案例中获取路径节点? 我的整个文件App.js:
export default class TreeVera extends Component {
constructor(props) {
super(props);
this.updateTreeData = this.updateTreeData.bind(this);
this.removeNode = this.removeNode.bind(this);
this.state = {
treeData: [{
title: (<div>
<input />
<button onClick={this.removeNode}>remove</button>
</div>),
}]
};
}
removeNode(e){
this.setState({
treeData: removeNodeAtPath({
treeData: this.state.treeData,
path: ????,
getNodeKey: ({node: TreeNode, treeIndex: number}) => {
console.log(number);
return number;
},
ignoreCollapsed: false,
})
})
}
updateTreeData(treeData) {
this.setState({ treeData });
}
render() {
return (
<div style={{ height: 600 }}>
<SortableTree
treeData={this.state.treeData}
onChange={this.updateTreeData}
/>
</div>
);
}
GitHub上的
答案 0 :(得分:4)
我解决了这个问题:
export default class Tree extends Component {
constructor(props) {
super(props);
this.updateTreeData = this.updateTreeData.bind(this);
this.addNode = this.addNode.bind(this);
this.removeNode = this.removeNode.bind(this);
this.state = {
treeData: [{
title: '',
}]
};
}
getChildContext() {
return { muiTheme: getMuiTheme(baseTheme) };
}
addNode(rowInfo){
let NEW_NODE = {title: ''};
let {node, treeIndex, path} = rowInfo;
path.pop();
let parentNode = getNodeAtPath({
treeData: this.state.treeData,
path : path,
getNodeKey: ({ treeIndex }) => treeIndex,
ignoreCollapsed : true
});
let getNodeKey = ({ node: object, treeIndex: number }) => {
return number;
};
let parentKey = getNodeKey(parentNode);
if(parentKey == -1) {
parentKey = null;
}
let newTree = addNodeUnderParent({
treeData: this.state.treeData,
newNode: NEW_NODE,
expandParent: true,
parentKey: parentKey,
getNodeKey: ({ treeIndex }) => treeIndex
});
this.setState({treeData: newTree.treeData});
}
removeNode(rowInfo) {
let {node, treeIndex, path} = rowInfo;
this.setState({ treeData : removeNodeAtPath({
treeData: this.state.treeData,
path: path, // You can use path from here
getNodeKey: ({node: TreeNode, treeIndex: number}) => {
// console.log(number);
return number;
},
ignoreCollapsed: false,
})
})
}
updateTreeData(treeData) {
this.setState({ treeData });
}
render() {
return (
<div style={{ height: 600 }}>
<SortableTree
treeData={this.state.treeData}
onChange={this.updateTreeData}
generateNodeProps={rowInfo => ({
buttons: [
<div style={divStyle}>
<TextField
hintText=""
multiLine={true}
rows={1}
rowsMax={4}
/><br />
<button label='Delete'
onClick={(event) => this.removeNode(rowInfo)}>Remove</button>
<button label='Add'
onClick={(event) => this.addNode(rowInfo)}>Add</button>
</div>,
],
style: {
height: '50px',
}
})}
/>
</div>
);
}
}