在我的源代码中,我用.current.clientHeight
测量的组件EditorBasic
的高度在调整窗口大小时会改变,这是不正确的,为了重现这个错误,我编写了下面的较小代码。
我使用aRef
来引用EditorBasic
,并期望得到它的高度。我期望下面的代码具有以下行为:
1.当我们点击“点击切换EditorBasic”时,通过updateTrigger
,EditorBasic
将触发handleResize
。
handleResize
调用calculateNextHeight
,calculateNextHeight
可以打印EditorBasic
的高度,以便我检查。
但我无法通过第一步;改变updateTrigger
不能触发handleResize
;不打印日志componentDidUpdate
。
有人知道为什么吗?
堆栈 lightning 战:https://stackblitz.com/edit/react-ts-j4pm8x?file=App.tsx,EditorBasic.tsx
import * as React from 'react';
import EditorBasic from './EditorBasic';
interface IAppProps {}
interface IAppState {
showEditorBasic: boolean;
updateTrigger: number;
}
export default class App extends React.Component<IAppProps, IAppState> {
aRef: any;
constructor(props) {
super(props);
this.state = {
showEditorBasic: false,
updateTrigger: 0,
};
this.aRef = React.createRef();
}
calculateNextHeight = () => {
console.log(
'this.aRef.current.clientHeight',
this.aRef.current.clientHeight
);
};
render() {
return (
<div>
<div
onClick={() =>
this.setState({
showEditorBasic: !this.state.showEditorBasic,
updateTrigger: this.state.updateTrigger + 1,
})
}
>
Click to toggle EditorBasic
</div>
{this.state.showEditorBasic && (
<div ref={this.aRef}>
<EditorBasic
calculateNextHeight={this.calculateNextHeight}
updateTrigger={this.state.updateTrigger}
/>
</div>
)}
</div>
);
}
}
import * as React from 'react';
interface IEditorBasicProps {
calculateNextHeight: any;
updateTrigger;
}
interface IEditorBasicState {}
export default class EditorBasic extends React.Component<
IEditorBasicProps,
IEditorBasicState
> {
handleResize() {
// console.log('handleResize');
this.props.calculateNextHeight();
}
componentDidMount() {
// console.log('componentDidMount');
window.addEventListener('resize', this.handleResize.bind(this));
}
componentDidUpdate(prevProps) {
console.log('componentDidUpdate');
if (this.props['updateTrigger'] !== prevProps['updateTrigger']) {
this.handleResize();
}
}
render() {
return (
<div>
<br />
<br />
EditorBasic {this.props.updateTrigger}
<br />
<br />
</div>
);
}
}
2条答案
按热度按时间8i9zcol21#
属性
showEditorBasic
完全重新创建了BasicEditor
,在这种情况下,组件将只触发componentDidMount
函数。尝试在
componentDidMount
内调用handleResize
,并在if
语句外呈现aRef
div。应用程序
编辑器基本
mgdq6dx12#
组件的React文档Did更新:
更新发生后立即调用。初始呈现时不调用。
当showEditorBasic存在时,您正在渲染EditorBasic,并且更改其 prop 与初始渲染同时进行。