这是我的组件代码。除此“ onResize”功能外,其他所有功能均正常运行。
class MyComponent extends Component {
constructor(props) {
super(props)
this.onResize = this.onResize.bind(this)
}
onResize = () => {
window.onresize = () => {
alert(true)
//I had tried with 'this.alert(true)' too
}
}
}
componentDidMount() {
this.onResize()
}
//rest of the code ommited
答案 0 :(得分:2)
您必须在componentDidMount
生命周期中添加事件监听器:
componentDidMount() {
window.addEventListener('resize', this.handleWindowResize)
}
请记住在卸载组件时删除事件侦听器,以避免内存泄漏:
componentWillUnmount() {
window.removeEventListener('resize', this.handleWindowResize)
}
答案 1 :(得分:0)
您需要添加事件监听器以调整大小
onResize() {
this.setState({
width: $(window).width(),
height: $(window).height()
})
}
componentWillMount() {
this.onResize();
}
componentDidMount() {
window.addEventListener("resize", this.onResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.onResize);
}