Skip to content

Instantly share code, notes, and snippets.

@tfanme
Created March 22, 2018 12:16
Show Gist options
  • Save tfanme/ed2a703efaa6c5040a29ec9f67168686 to your computer and use it in GitHub Desktop.
Save tfanme/ed2a703efaa6c5040a29ec9f67168686 to your computer and use it in GitHub Desktop.
/**
* 支持检索嵌套表格
* @param key
*/
getNestedRowByKey(key, data = this.state.data) {
if (data.some(item => item.key === key)) {
return data.filter(item => item.key === key)[0]
}
for (let i = 0; i < data.length; i++) {
const item = data[i]
if (item.children) {
const row = this.getNestedRowByKey(key, item.children)
if (row) {
return row
}
}
}
return null
}
remove(key) {
const newData = this.removeNestedRowByKey(key);
// const newData = this.state.data.filter(item => item.key !== key);
this.setState({ data: newData });
this.props.onChange(newData);
}
removeNestedRowByKey(key, data = this.state.data) {
if (data.some(item => item.key === key)) {
return data.filter(item => item.key !== key)
}
for (let i = 0; i < data.length; i++) {
// const item = data[i]
if (data[i].children) {
data[i].children = this.removeNestedRowByKey(key, data[i].children)
}
}
return data
}
insertNestedRow(parentKey, data) {
const newItem = {
key: `NEW_TEMP_ID_${this.index}`,
originalName: '',
paramName: '',
paramType: 'string',
paramAlias: '',
editable: true,
isNew: true,
}
if (data.some(item => item.key === parentKey)) {
for (const row of data) {
if (row.key === parentKey) {
if (!row.children) {
row.children = []
}
row.children.push(newItem)
break
}
}
return data
}
for (let i = 0; i < data.length; i++) {
if (data[i].children) {
data[i].children = this.insertNestedRow(parentKey, data[i].children)
}
}
return data
}
newParameter = (parentKey) => {
return () => {
// console.log('parentKey = ', parentKey, ', index = ', this.index)
const newData = [...this.state.data];
if (!parentKey) {
newData.push({
key: `NEW_TEMP_ID_${this.index}`,
originalName: '',
paramName: '',
paramType: 'string',
paramAlias: '',
editable: true,
isNew: true,
});
} else {
this.insertNestedRow(parentKey, newData)
}
this.index += 1;
this.setState({ data: newData });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment