如何在深度嵌套的变量上使用 setState

How to use setState on deeply nested variable

我目前正在将 table 保存到 this.state 中,您可以在此处看到

this.setState({    
      table: 
        <div  id='link-table' className="table-panel-table" style={{ width: "100%" , height: height - 35, overflow:'auto' }}>
          {columns}
          {rows}
        </div>      
    });

然后在render函数中直接使用table变量在网站上显示:

render(){ return (this.state.table) }

(如果出于某种原因这是个坏主意,请告诉我)

我目前遇到的问题是,当您单击它时,我想将其中一个单元格变成一个输入字段(显然是它上面的一个表单元素)。 我想知道如何最好地更改 this.state.table 以便在我更改单元格时它会重新渲染。

如果我使用它,它不起作用

this.state.table.props.children[1][row].props.children[cell].props.children = form_element;

根据我的理解,我需要使用 this.setState() 来相应地更改它,但是我很难编写代码来针对 this.state.table 中的特定嵌套变量。

我要

const { table } = this.state;
let temp_table = {...table, props: {...table.props, children: [...table.props.children]}}

但后来卡住了,因为我不知道如何继续 .children[1][row]

您不需要将 table 存储在状态中,您可以只存储行和列数据,这样您就不必处理在 table 中查找元素的问题。不在状态中存储jsx元素,只存储数据生成视图。

render(){ 
  return (
    <div  id='link-table' className="table-panel-table" style={{ width: "100%" , height: height - 35, overflow:'auto' }}>
      {generateColumns(this.state.columns)}
      {generateRows(this.state.rows)}
    </div>      
)

}

您也不应该直接操作 dom 元素来改变它们的外观。 React 的做法是根据元素的状态生成元素,并根据它们的状态渲染不同的组件。我不知道你是如何生成生成行和列的,但下面的方法可能会给出一个想法:

generateRows= (rows) => {

  return rows.map(row => { 
    if(row.shouldHaveFormElement) {
        return <RowComponentWithFormElement></RowComponentWithFormElement>
    }else {
        return <NormalRowElement></NormalRowElement>
    }
}

}