请这样做并让我知道结果。没有构造函数的类可能会有奇怪的行为。还要检查一下:为什么我们写超级道具是因为使用构造函数的原因。
export default class Shoe extends Component<{ shoe: { asset:string, name:string, price:number }, handleShoePos:Function }> {
// add this
constructor(props){ // use some tsx behavior if you want
super(props);
this.cardRef = React.createRef<HTMLDivElement>();
}
componentDidMount() {
window.addEventListener( 'resize', this.handleResize );
this.handleResize();
}
handleResize = () => {
const { handleShoePos } = this.props;
const width = this.cardRef.current?.clientWidth;
if( width ) {
handleShoePos( width / 2 );
}
}
render() {
const { asset, name, price } = this.props.shoe;
return (
<div ref={ this.cardRef } className="shoe_card">
......
</div>
);
}
}