首页 > 解决方案 > 在再次打开之前卸载或移除先前打开的组件

问题描述

我有一个表格的内联编辑组件。每当我单击表格单元格时,它都会打开一个小的编辑窗口来编辑它。

问题 - 如果我单击另一个单元格,它会打开一个新的编辑窗口,最终会在屏幕上显示多个编辑窗口。

需要建议以删除/卸载编辑窗口的先前实例。删除 DOM 元素会引发未捕获的异常。

Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

编辑---

编辑组件代码 -

class TextEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = { isInlineEditVisible: false };
    }

    render() {
        return (
            <span
                style={{
                    marginLeft: '10px',
                }}
            >
               <CellAction>
                   <EditIconButton
                       size={16}
                       onClick={() => {
                            this.setState({ isInlineEditVisible: true });
                     }}
                   />
               </CellAction>

                {this.state.isInlineEditVisible && (
                        <InlineEdit
                            label={this.props.label}
                            value={this.props.param.dataPoint}
                            onSave={(value) => {
                                this.props.onSave(value, this.props.param);
                            }}
                            onCancel={() => {
                                this.setState({ isInlineEditVisible: false });
                            }}
                        />
                    </span>
                )}
            </span>
        );
    }
}

我将此组件编写为 InlineEdit 组件的包装器,因为我需要它与多列表的每个单元格一起使用。

标签: reactjs

解决方案


这是想法。让我们将循环单元格的包装器称为CellWrapper单元格组件的 Cell。

const Cell = ({ cell, editCellId, setEditCellId }) => (
 <div> 
   // Cell code


   <EditIconButton
     size={16}
     onClick={() => {
       setEditCellId({ editCellId: cell.id });
     }}
   />

   // EditWindow Code
   {editCellId && editCellId === cell.id && <EditWindow />}
 </div>
)

class CellWrapper extends Component{
   state = {
      editCellId: null
   }
   render(){
      const { cells } = this.props;
      return(
        <div>{cells.map( cell => 
          <Cell
            cell={cell}
            editCellId={this.state.editCellId}
            setEditCellId={(editCellId) => this.setState({editCellId})}
          />
         )
        }</div>
      ) 
   }
}

推荐阅读