reactjs 如何在react中间添加动态列?

0g0grzrc  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(65)

我们使用ag-grid,必须在第三个索引中动态添加一个列。我可以使用以下代码在react中动态添加一个列:

let headers = $this.state.empHeaders;
      empList.org.forEach(item => {
        if(item.check === 'xyz'){
          headers.push({ field:'name', headerName:'NAME',cellRenderer:'empName'});
        }
      })

字符串
如何指定在哪里添加动态列?例如:如何在第三个位置添加新列?

n3ipq98p

n3ipq98p1#

我认为你是在正确的位置。只是你是推在年底。所以改变代码插入项目的第三个位置或您的特定位置。

let headers = $this.state.empHeaders;

empList.org.forEach(item => {
  if (item.check === 'xyz') {
    // Specify the index where you want to add the new column (e.g., 2 for the third position)
    const insertionIndex = 2;

    // Check if the index is within the valid range
    if (insertionIndex >= 0 && insertionIndex <= headers.length) {
      // Use splice to insert the new column at the specified index
      headers.splice(insertionIndex, 0, { field: 'name', headerName: 'NAME', cellRenderer: 'empName' });
    } else {
      console.error(`Invalid insertion index: ${insertionIndex}`);
    }
  }
});

// Update the state with the modified headers
$this.setState({ empHeaders: headers });

字符串

相关问题