我尝试使用带有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。
发布于 2018-10-03 18:42:28
根据我在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>
);
}
}
https://stackoverflow.com/questions/51845597
复制相似问题