該問題在代碼片段中的評論中大致概括。當我在constructor
中綁定this._setSize
時,它從不知道this.container
- 即使在componentDidMount
中調用。我究竟做錯了什麼?謝謝!在React ComponentDidMount中獲取引用和附加事件偵聽器的正確方法?
export default class MyComponent extends React.Component {
constructor() {
super()
this._setSize = this._setSize.bind(this)
}
componentDidMount() {
const container = this.container // <div></div> :)
this._setSize()
window.addEventListener('resize', this._setSize)
}
componentWillUnmount() {
window.addEventListener('resize', this._setSize)
}
_setSize() {
const container = this.container // undefined :(
const containerSize = {
x: container.offsetWidth,
y: container.offsetHeight
}
this.setState({ containerSize })
}
render() {
return (
<div ref={node => this.container = node}>
</div>
)
}
}