Component Radid增强组件的ComponentDidMount中的绑定范围

问题描述 投票:2回答:1

我正在研究名为ProjectCard的React组件,它包含两个div。第二个div有一个下拉列表,当用户将鼠标悬停在卡片上或点击了下拉列表时,我想突出显示整张卡片。我使用Radium为前面的组件添加悬停功能,但是为了将这个新逻辑用于突出显示,我在卡状态中跟踪了isActiveisLocked。例如,当鼠标在以下函数中进入或离开组件时,我切换isActive。 (我在构造函数中绑定了toggleActive

toggleActive () {
  console.log(this);
  this.setState({
    isActive: !this.state.isActive
  });
}

但是,我收到一个错误,我无法在安装组件之前设置状态。稍微捅了一下并在各种函数中记录了this,这似乎是Radium的一个问题。我在导出中使用了Radium包装器,如下所示:export default Radium(ProjectCard);,以及上面的toggleActiveProjectCard记录为this,而componentDidMountRadiumEnhancer(ProjectCard)记录为this。一个无镭的解决方法是使用HoC,但我想我可以通过调整我绑定的范围来解决这个问题,所以我将函数绑定移动到componentDidMount,如下所示。 (使用箭头函数自动绑定范围,如来自构造函数的调用)

constructor (props: Props) {
  super(props);
  this.state = {
    isActive: true,
    isLocked: false
  };
}

componentDidMount() {
  console.log(this);
  this.onClick = this.onClick.bind(this);
  this.toggleLock = this.toggleLock.bind(this);
  this.toggleActive = this.toggleActive.bind(this);
  console.log("mounted, functions bound");
  //console.log(this.toggleActive);
  this.toggleActive();
  //manual fix, stackoverflow this.
}

但是,在componentDidMount中绑定并将鼠标悬停在组件上没有引起任何更改,而toggleActivethis记录为未定义。没有运气,修复似乎不起作用。

但是,在尝试调试时,我手动调用toggleActive(如上所示)并记录了RadiumEnhancer(ProjectCard)(我想要的范围)并奇迹般地,悬停功能开始工作(其他功能也得到了正确的范围)。

我的问题是:

  • 不正确的范围/ Radium是否导致setState错误?除了setState之外,代码中没有异步操作。
  • 如果是这样,这个修复是否合法?为什么在我改变了this的范围之后它不起作用?
  • 为什么手动调用toggleActive为所有函数提供正确的this和范围?

谢谢!这是相关代码的pastebin:https://pastebin.com/MRKw2APw

javascript reactjs ecmascript-6 radium
1个回答
0
投票

如果删除渲染函数中的所有内容并只渲染一个简单的p标记,则会看到“this”和“toggleActive”未定义。仔细检查渲染功能。

© www.soinside.com 2019 - 2024. All rights reserved.