1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-08 18:30:53 +00:00
Files
seahub/frontend/src/components/common/fixed-width-table.js

50 lines
1.5 KiB
JavaScript
Raw Normal View History

import React, { useState, useEffect, useRef, useMemo } from 'react';
import PropTypes from 'prop-types';
const FixedWidthTable = ({ className, headers, theadOptions = {}, children }) => {
const [containerWidth, setContainerWidth] = useState(0);
const fixedWidth = useMemo(() => headers.reduce((pre, cur) => cur.isFixed ? cur.width + pre : pre, 0), [headers]);
const containerRef = useRef(null);
useEffect(() => {
const container = containerRef.current;
const handleResize = () => {
if (!container) return;
setContainerWidth(container.offsetWidth);
};
const resizeObserver = new ResizeObserver(handleResize);
container && resizeObserver.observe(container);
return () => {
container && resizeObserver.unobserve(container);
};
}, []);
return (
<table ref={containerRef} className={className}>
<thead { ...theadOptions }>
<tr>
{headers.map((header, index) => {
const { width, isFixed, children: thChildren, className } = header;
const validWidth = isFixed ? width : (containerWidth - fixedWidth) * width;
return (<th key={index} style={{ width: validWidth }} className={className}>{thChildren}</th>);
})}
</tr>
</thead>
<tbody>
{children}
</tbody>
</table>
);
};
FixedWidthTable.propTypes = {
className: PropTypes.string,
headers: PropTypes.array,
theadOptions: PropTypes.object,
children: PropTypes.oneOfType([PropTypes.string, PropTypes.node, PropTypes.number]),
};
export default FixedWidthTable;