这是我的代码,目前有效。 它检测组件的宽度-表格,然后在包装器上设置该宽度。
import React from 'react';
type shapeWrapper = {
filtered: string[]
};
type shapeState = {
tableWidth: string,
visibility: string
};
class Wrapper extends Component<shapeWrapper, shapeState> {
private refParent = React.createRef<HTMLElement>();
public ref = React.createRef<HTMLTableElement>();
// replace above with
/*
public refTable = React.createRef<HTMLTableElement>(),
public refTds:HTMLTableElement[] = filtered.map(item => React.createRef<HTMLTableElement>());
public ref = {
refTable,
refTds
}
*/
constructor(props: shapeWrapper) {
super(props);
this.setWrapperWidth = this.setWrapperWidth.bind(this);
this.state = {
tableWidth: '0',
visibility: 'hidden'
};
}
setWrapperWidth(tableWidth:string) {
this.setState({
tableWidth,
visibility: 'visible'
});
}
render() {
const {filtered} = this.props;
const {tableWidth} = this.state;
const {setWrapperWidth} = this;
const {ref, refParent} = this;
return (
<section ref={refParent} style={{width: tableWidth}}>
<Table
filtered={filtered}
ref={ref}
onMount={tableWidth => {setWrapperWidth(tableWidth);}}
/>
</section>
);
}
};
export default Wrapper;
import React, {forwardRef, useEffect} from 'react';
export type shapeTable = {
filtered: string[][],
onMount: (tableWidth:string) => void
};
type Ref = HTMLTableElement;
const Table = forwardRef<Ref, shapeTable>(({filtered, onMount}, ref) => {
useEffect(() => {
if(ref && typeof ref !== 'function' && ref.current) {
const tableWidth:string = window.getComputedStyle(ref.current).getPropertyValue("width");
onMount(tableWidth);
}
}, [ref]);
return filtered.length
? (
<table ref={ref}>
<tr >
{filtered.map((item, ind) => (
<th>{item}</th>
))}
</tr>
</table>
)
: null
});
export default Table;
我现在要做的是检测td列的宽度。 我需要提供多个裁判,但所有尝试似乎都失败了。 Typescript期望过去的引用始终是目标,而不是数组。我如何在另一端的forwardRef上传递和接收它: 这是我想做的一个例子,但是打字稿不希望'ref'是一个对象,更不用说数组了。
public refTable = React.createRef<HTMLTableElement>(),
public refTds:HTMLTableElement[] = filtered.map(item => React.createRef<HTMLTableElement>());
public ref = {
refTable,
refTds
}