Reactstrap 工具提示导致错误:无法在 dom 中识别目标“TooltipExample”

IT技术 reactjs reactstrap
2021-05-09 21:04:58

我遵循了有关 Reactstrap 中工具提示的代码示例

constructor(props) {
  super(props);
  this.state = {
    tooltipOpen: true
  };
}
.
.
.
render() {
  return (
    <div>
      <p>Somewhere in here is a <a href="#" id="TooltipExample">tooltip</a>.</p>
      <Tooltip 
        placement="right" 
        isOpen={this.state.tooltipOpen} 
        target="TooltipExample" 
        toggle={this.toggle}>
        Hello world!
      </Tooltip>
    </div>
  ) 
}

我收到以下错误:

错误:无法在 dom 中识别目标“TooltipExample”,提示:检查拼写

如果初始状态为 ,则一切正常tooltipOpen: false但是我希望在用户加载页面时出现工具提示...

我该怎么办?

3个回答

在构造函数中, tooltipOpen 应该是false.

然后,在 componentDidMount 中,将 tooltipOpen 从 切换falsetrue

这是代码:

constructor(props) {
  super(props);
  this.state = {
    tooltipOpen: false,
  };
}

componentDidMount() {
  this.setState({
    tooltipOpen: true,
  });
}

由于引入了 React Hooks,可以使用以下方法避免此错误。

import React, { useRef } from 'react'
import { UncontrolledTooltip } from 'reactstrap'

const ToolTipExample = () => {

    const ref = useRef(null)

    return (
        <div >
            <p ref={ref}>Hello World</p>
            <UncontrolledTooltip target={ref}>
                Tooltip message goes here :D
            </UncontrolledTooltip>
        </div>
    )
}

这也适用于Tooltip组件。

我也遇到了同样的问题,问题是初始值,初始值必须是false如果你把truepopover作为初始值寻找target还不能渲染元素,所以如果你想打开popover作为组件渲染更新componentDidMount钩子中的状态

/* initial value must be false */
state = { isPopoverOpen: false };

componentDidMount() {
  this.setState({
    isPopoverOpen: true,
  });
}