传递给渲染道具时,对DOM实例的引用未定义

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

我正在尝试使用一些嵌套的渲染道具来组成一个按钮,该按钮可选择带一个图标,然后可选择带一个工具提示,该图标将在图标悬停或点击时显示。要做到这一点,我想我需要将对Icon的引用传递给子Tooltip组件。

根据我所读的here,我正在做什么

  // Icon

  componentDidMount() {
    this.iconInstance = ReactDOM.findDOMNode(this);
    console.log('Icon mounted, instance', this.iconInstance);
  }

  render() {
    console.log('Icon render iconInstance', this.iconInstance);
    return (
      <span style={{ display: 'inline' }}>
        <span>{this.props.iconText}</span>
        {this.props.tooltip({ iconInstance: this.iconInstance })}
      </span>
    );
  }

然后在Tooltip内,将添加一个听众

  componentDidMount() {
    console.log('Tooltip mounted', this.props);
    // fails because iconInstance is undefined
    // this.props.iconInstance.addEventListener(
    //   this.props.mouseEvent,
    //   this.showTooltip
    // );
  }

在我设置this.iconInstance之后,它可以被记录下来,因此它似乎正常工作。但是在渲染功能中我得到了未定义。

可能有一种方法可以使用forwardRef来做到这一点,但我找不到一种方法将Tooltip组件作为渲染道具从App组件传递到Icon并添加一个ref道具,例如,{this.props.tooltip(this.iconInstance)}得到一个错误说你不能传递这样的参考,它会失败。

Full code

javascript reactjs functional-programming jsx
1个回答
-2
投票

ComponentDidMount是第一次调用render方法后执行的方法。它是在执行render方法之前调用的ComponentWillMount方法。

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