【问题标题】:react-grid-layout How can I resize components on the grid?react-grid-layout 如何调整网格上组件的大小?
【发布时间】:2019-01-21 13:22:33
【问题描述】:

我尝试使用带有 react-grid-layout 的自定义组件。但是,我无法让它工作。 当我将组件放入 div 中时,我可以调整该 div 的大小,但组件本身不会随之调整大小。 当我将组件直接放在网格标签内时,我根本无法调整大小或移动它,并且网格的边框也不匹配组件的边框。

这是我的 index.js 的代码:

function App() {
return (
<div className="App" style={{ background: "grey" }}>
  <GridLayout className="layout" cols={16} rowHeight={10} width={500}>
    <div key="a" data-grid={{ x: 0, y: 0, w: 5, h: 10 }}>
      <TestComponent
        style={{
          color: "green",
          height: "auto",
          width: "auto",
          background: "red"
        }}
      />
    </div>

    <div
      key="b"
      data-grid={{ x: 5, y: 0, w: 3, h: 3 }}
      style={{ background: "green" }}
    >
      this works fine
    </div>

    <TestComponent
      key="c"
      data-grid={{ x: 1, y: 0, w: 2, h: 2 }}
      style={{
        color: "blue",
        height: "auto",
        width: "auto",
        background: "black"
      }}
    />
  </GridLayout>
</div>
);
}

我已经在代码沙箱上上传了完整的示例,包括 TestComponent: https://codesandbox.io/s/7zl7mm90m0

如何在网格上正确实现自定义组件?

最好的问候,

W.

【问题讨论】:

    标签: reactjs react-grid-layout


    【解决方案1】:

    根据我在 react-grid-layout 方面的专业知识,您必须使用 div 来设置 data-grid 属性,并且在该 div 中您可以传递您的自定义组件。否则,它将无法正常工作。 这将起作用:

    <div key="a" data-grid={{ x: 0, y: 0, w: 5, h: 10 }}>
      <TestComponent
        style={{
          color: "green",
          height: "auto",
          width: "auto",
          background: "red"
        }}
      />
    </div>
    

    否则,您可以为 n-component 创建一个函数并将该函数传递给网格,例如:

    class App {
        renderElement(element) {
          return <div key={element} data-grid={{ x: 0, y: 0, w: 5, h: 10 }}>
              <TestComponent element={element} />
            </div>
        }
        render(){
        return (
        <div className="App" style={{ background: "grey" }}>
          <GridLayout className="layout" cols={16} rowHeight={10} width={500}>
            {[1,2,3,4,5].map(element=>this.renderElement(element))}
          </GridLayout>
        </div>
        );
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 2021-03-11
      • 2021-04-09
      • 2023-02-24
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      相关资源
      最近更新 更多