【问题标题】:Reactstrap Tooltip throws target could not be identified in the dom error with dynamic IDsReactstrap 工具提示抛出目标无法在具有动态 ID 的 dom 错误中识别
【发布时间】:2020-09-11 10:24:09
【问题描述】:

我有一个完美工作的自定义 Reactstrap Tooltip 组件,我在我的表单中使用它。但是,我最近发现,如果我多次使用相同的 name 属性,则会出现目标 ID 冲突,这会导致某些工具提示不显示。

因此,我决定在工具提示中附加一个随机字符串,以便获得这样的唯一 ID:

// instead of just `Tooltip-${name}`, I use `Math.random()`:
const tooltipId = `Tooltip-${name}-${Math.random().toString(36).substr(2, 5)}`;

然后我使用刚刚创建的tooltipId 常量作为id 和target。

但是,一旦用户将鼠标悬停在(i) 图标上,就会产生以下错误:

The target 'Tooltip-tp1-27tha' could not be identified in the dom, tip: check spelling

谁能解释一下为什么只有在生成随机 ID 时才会出现这种情况?

这是一个演示问题的沙盒: https://codesandbox.io/s/fast-shape-thj00?file=/src/CustomTooltip.jsx

【问题讨论】:

标签: javascript reactjs reactstrap


【解决方案1】:

在创建组件时创建你的 tooltipId,而不是在 render 方法中。 因为状态发生了变化,所以会重新渲染,因此有一个新的 tooltipid。

class CustomTooltip extends Component {
  tooltipId = `Tooltip-${this.props.name}-${Math.random().toString(36).substr(2, 5)}`

...

【讨论】:

  • 谢谢,我想通了,但我还是不明白为什么状态会改变?是Math.random() 触发了重新渲染吗?
  • 不,tooltipOpen 的状态在悬停时会发生变化,这就是它重新渲染的原因
  • 对,点赞?
猜你喜欢
  • 2018-10-31
  • 2018-07-02
  • 1970-01-01
  • 2020-12-27
  • 2020-03-23
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多