我想要一个在单击表格行时弹出的模式。当我单击表格组件中的一行时,模式正在打开。但是我没有用 css 得到想要的结果。单击一行时,我希望它与页面上的所有内容重叠。现在它显示在页面顶部,我看不到其中的内容。
//Modal.js
import React from "react";
import Table from "react-bootstrap/Table";
export default function Modal() {
return (
<div className="modalContainer">
<Table responsive="true" size="sm" striped bordered hover>
<thead>
<tr>
<th>Own Product</th>
<th>Competitors Products</th>
</tr>
</thead>
<p>Brand</p>
<p>Category</p>
<p>In Stock</p>
<p>Name</p>
<p>Price</p>
<p>Product Code</p>
<p>Product Link</p>
</Table>
</div>
);
}
//Code from Table.js
render() {
let { isLoaded, products } = this.state; //instead of typing
this.state all the time
if (!isLoaded) {
return <Loading />;
} else {
return (
<div className="tableContainer">
{this.props.rows}
<Table responsive="true" size="sm" striped bordered hover>
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Match ID</th>
<th>Match Score</th>
<th>Match Name</th>
<th>Match Price</th>
<th>Match State</th>
</tr>
</thead>
<tbody>
{products.map(product => (
//use filter instead to show only the matched ones
<tr key={product.id} onClick={() => this.toggleModal()}>
<td>{product.id}</td>
<td>{product.name}</td>
<td>{product.matches[0].id}</td>
<td>{Math.round(product.matches[0].score)}</td>
<td>{product.matches[0].name}</td>
<td>{product.matches[0].price}</td>
<td>{product.matches[0].matchLabel}</td>
</tr>
))}
{this.state.modalOpen ? <Modal /> : null}
</tbody>
</Table>
</div>
);
}
}
//CSS
.tableContainer {
position: relative;
width: 100%;
height: 100%;
}
.modalContainer {
margin: -30% auto;
position: absolute;
width: 100%;
height: 100%;
justify-content: center;
border: 1px solid black;
z-index: 1;
left: 0;
top: 0;
overflow: auto;
background-color: rgba(219, 239, 250);
}
最佳答案
问题是您的 tableContainer
是position:relative
,它会重新设置其子项的定位上下文。所以,你的 <Modal>
相对于 tableContainer
绝对定位而不是浏览器窗口。
您可以将您的 css 更改为例如您的模态框position:fixed
或者将你的模态移出你的 tableContainer
像这样:
return (
<>
{this.state.modalOpen ? <Modal /> : null}
<div className="tableContainer">
{this.props.rows}
<Table responsive="true" size="sm" striped bordered hover>
//....//
</Table>
</div>
</>
关于css - 在 React 中实现模态的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58012954/