我正在尝试使用一些嵌套的渲染道具来组成一个按钮,该按钮可选择带一个图标,然后可选择带一个工具提示,该图标将在图标悬停或点击时显示。要做到这一点,我想我需要将对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)}
得到一个错误说你不能传递这样的参考,它会失败。
ComponentDidMount是第一次调用render方法后执行的方法。它是在执行render方法之前调用的ComponentWillMount方法。