反应网格布局 如何调整网格上的组件大小?



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

这是我的索引的代码.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>
);
}

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

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

此致敬意

W.

根据我在 react-grid-layout 方面的专业知识,您必须使用div 来设置数据网格属性,并且在该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 分量创建一个函数并将该函数传递给网格,如下所示:

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>
);
}
}

最新更新