首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >跨对象保留此上下文

跨对象保留此上下文
EN

Stack Overflow用户
提问于 2018-06-07 20:55:04
回答 1查看 43关注 0票数 0

我正在使用this工具提示来显示一些信息。当单击其中一个选项时,我希望显示下一个工具提示。这种转换是由库作者通过ref设置的,在这种情况下,ref在字符串字面量时工作得很好。但是,在React16+中不推荐使用字符串文字。

解决方法是使用createRef,我就是这么做的。它适用于第一个弹出窗口,但在必须转换时失败,因为this引用了使用它的即时对象。

下面是我写的代码。如何更改它,使this引用正确的对象?

//Constructor
constructor() {
 super();
 this.firstToolTip= React.createRef();
 this.secondToolTip = React.createRef();
}
//Body of render method
<PopoverTooltip
   ref={this.firstToolTip}
   buttonComponent={button}
   items={[
     {
       label: 'Some text for the tootip',
       onPress: () => {                     
         this.refs[this.secondToolTip].toggle();
       }
     }
   ]}
/>

<PopoverTooltip
   ref={this.secondToolTip}
   buttonComponent={button}
   items={[
     {
       label: 'Some text for the tootip',
       onPress: () => {}
     }
   ]}
/>

我知道,正如我在这里读到的其他帖子所提到的那样,我可以绑定this,但createRef返回undefined,因此这是非常不可能的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 21:23:41

尝试像这样绑定click函数。

//Constructor
constructor() {
  super();
  this.firstToolTip= React.createRef();
  this.secondToolTip = React.createRef();
  this.clickOnFirstTooltip=this.clickOnFirstTooltip.bind(this);
}
 //Added func
 clickOnFirstTooltip(){
   // ref.current to acccesss the tooltip 
   this.secondToolTip.current.toggle();
 }
//Body of render method
<PopoverTooltip
  ref={this.firstToolTip}
  buttonComponent={button}
  items={[
    {
   label: 'Some text for the tootip',
    onPress:this.clickOnFirstTooltip
   }
  ]}
/>

<PopoverTooltip
  ref={this.secondToolTip}
  buttonComponent={button}
  items={[
    {
      label: 'Some text for the tootip',
      onPress: () => {}
     }
   ]}
  />
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50741777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档