React:SlickGrid 需要一个有效的容器,#myGrid 在 DOM 中不存在

React: SlickGrid requires a valid container, #myGrid does not exist in the DOM

我多次尝试修复该问题时反复遇到此错误。在这里,我给出了我的示例代码。

index.js,

const app = (
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
    </Provider>

);
ReactDOM.render(app, document.getElementById("root"));

App.js,

import React, { Component } from 'react';

import SlickGrid1 from "./containers/Grids/SlickGrid/GridExamples/Example1";

class App extends Component {
  render () {


    return (
      <div>
          <div id="myGrid"></div>
          <SlickGrid1 />
      </div>
    );
  }
}

export default App;

Example1.js,

import {Grid, Data} from 'slickgrid-es6';
import data from "../example-data";
const columns = [
  { id: "title", name: "Title", field: "title", maxWidth: 100, minWidth: 80 },
  { id: "duration", name: "Duration", field: "duration", resizable: false },
  { id: "%", name: "% Complete", field: "percentComplete" },
  { id: "start", name: "Start", field: "start" },
  { id: "finish", name: "Finish", field: "finish" },
  { id: "effort-driven", name: "Effort Driven", field: "effortDriven" }
];

const options = {
  enableCellNavigation: true,
  enableColumnReorder: true,
  forceFitColumns: !true,
  frozenColumn: 0,
  frozenRow: 1
};

const dataView = new Data.DataView();
dataView.setItems([ ...data ]); // some data


export default new Grid("#myGrid", dataView, columns, options);

尽管我在 <SlickGrid1 /> 组件渲染之前定义了 '#myGrid' div,它总是抛出相同的错误。我该如何解决这个问题?

我认为您误解了 new Grid 在您的代码中创建的内容。您试图将其导出为 React 组件,而实际上它只是基于现有的 DOM 元素创建网格。由于您在导出中调用 new Grid ,因此您正在导出一个实例。它将尝试在您的 App 组件的渲染功能被触发之前创建 Grid,这意味着没有有效的目标可以绑定到。尝试导出一个工厂函数,像这样:

Example1.js

import {Grid, Data} from 'slickgrid-es6';
import data from "../example-data";
const columns = [
  { id: "title", name: "Title", field: "title", maxWidth: 100, minWidth: 80 },
  { id: "duration", name: "Duration", field: "duration", resizable: false },
  { id: "%", name: "% Complete", field: "percentComplete" },
  { id: "start", name: "Start", field: "start" },
  { id: "finish", name: "Finish", field: "finish" },
  { id: "effort-driven", name: "Effort Driven", field: "effortDriven" }
];

const options = {
  enableCellNavigation: true,
  enableColumnReorder: true,
  forceFitColumns: !true,
  frozenColumn: 0,
  frozenRow: 1
};

const dataView = new Data.DataView();
dataView.setItems([ ...data ]); // some data

export default () => new Grid("#myGrid", dataView, columns, options);

然后在您的 App 组件的 componentDidMount 挂钩中调用此工厂函数:

App.js

import React, { Component } from 'react';

import SlickGrid1 from "./containers/Grids/SlickGrid/GridExamples/Example1";

class App extends Component {
  componentDidMount() {
    SlickGrid1();
  }
  render () {


    return (
      <div>
          <div id="myGrid"></div>
      </div>
    );
  }
}

export default App;

看到这个working example(我省略了测试数据)