去抖动和反应窗口调整此参考问题的大小

pet*_*gan 4 javascript this ecmascript-6 lodash reactjs

我正在使用react和 lodash 的debounce方法。我遇到的问题是当用户调整窗口大小时更新状态。

我遇到的问题是,当用户在此函数中调整窗口大小时,this它指的window是与组件相反的组件:

window.addEventListener('resize', this.delayedCallback)

我尝试过设置const that = this等,但无法获得正确的范围。有谁知道如何解决这个问题?

见下面的代码:

class Card extends Component {

  constructor(props) {
    super(props)
    this.state = {
      cardElWidth: null
    }
    this.delayedCallback = debounce(this.setCardWidth, 1000);
    this.CardEl = React.createRef()
  }

  componentDidMount () {
    this.setCardWidth()
    window.addEventListener('resize', this.delayedCallback)
  }

  setPlayerCardWidth() {
    this.setState({
      cardElWidth: this.CardEl.current.offsetWidth
    })
  } ... rest of code
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 5

在构造函数中绑定setCardWidth方法this

constructor(props) {
  super(props)
  this.state = {
    cardElWidth: null
  }
  this.setCardWidth = this.setCardWidth.bind(this)
  this.delayedCallback = debounce(this.setCardWidth, 1000)
  this.CardEl = React.createRef()
}
Run Code Online (Sandbox Code Playgroud)

或者通过直接在 debounce 表达式中绑定甚至更短:

constructor(props) {
  super(props)
  this.state = {
    cardElWidth: null
  }
  this.delayedCallback = debounce(this.setCardWidth.bind(this), 1000)
  this.CardEl = React.createRef()
}
Run Code Online (Sandbox Code Playgroud)

您可以将 转换setCardWidth为类属性,并使用箭头函数自动绑定到 ,而不是在构造函数中使用 bind this

注意:这需要 babel 的plugin-proposal-class-properties

setPlayerCardWidth = () => {
  this.setState({
    cardElWidth: this.CardEl.current.offsetWidth
  })
}
Run Code Online (Sandbox Code Playgroud)

如果使用类属性,也可以删除构造函数:

class Card extends Component {
  state = {
    cardElWidth: null
  }

  CardEl = React.createRef()

  componentDidMount() {
    this.setCardWidth()
    window.addEventListener('resize', this.delayedCallback)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.delayedCallback)
  }

  delayedCallback = debounce(this.setCardWidth, 1000)

  setPlayerCardWidth = () => {
    this.setState({
      cardElWidth: this.CardEl.current.offsetWidth
    })
  }
}
Run Code Online (Sandbox Code Playgroud)