【发布时间】:2019-07-18 22:37:54
【问题描述】:
我得到了按钮组件,它有另一个子组件来显示工具提示。我将 ref 传递给 <Tooltip> 组件,我将事件侦听器附加到 mouseEnter 和 mouseLeave 事件到我的按钮。
<Button
ref={this.buttonRef}
type={this.props.type}
className={this.props.className}
disabled={this.props.operationIsActive || (this.props.enabled == undefined ? undefined : !this.props.enabled)}
onClick={this.props.onClick}
onSubmit={this.props.onSubmit}
icon={this.props.icon}
>
{this.props.children}
</Button>
<Tooltip domRef={this.buttonRef} text={this.props.tooltip} />
这是我的Tooltip 组件
export class Tooltip extends ComponentBase<TooltipProps, TooltipState> {
private documentRef = null;
public componentDidMount() {
super.componentDidMount();
this.documentRef = this.props.domRef
if (this.props.domRef) {
const dom = this.props.domRef.current;
dom.element.addEventListener("mouseenter", this.showTooltip);
dom.element.addEventListener("mouseleave", this.hideTooltip);
}
}
public componentWillUnmount() {
if (this.documentRef) {
const dom = this.documentRef.current;
if (dom) {
dom.element.removeEventListener("mouseenter", this.showTooltip);
dom.element.removeEventListener("mouseleave", this.hideTooltip);
}
}
}
private showTooltip = (): void => {
this.updateState({ isTooltipVisible: true })
}
private hideTooltip = (): void => {
this.updateState({ isTooltipVisible: false })
}
private getStyles(position: any): React.CSSProperties {
const css: React.CSSProperties = {
left: position[0].left,
top: position[0].top + 40,
}
return css;
}
public render() {
if (!this.props.domRef.current) {
return null;
}
if(!this.state.isTooltipVisible)
{
return null;
}
const position = this.props.domRef.current.element.getClientRects();
const css = this.getStyles(position);
return ReactDOM.createPortal(<div style={css} className="tooltip">{this.props.text}</div>, document.getElementById(DomRoot) )
}
}
一切正常,但是当 onClick 事件在按钮上触发时(例如,我得到的按钮只为某些组件设置新状态,然后将呈现简单的 div),componentWillUnmount 方法被触发并且 ref 丢失所以我无法删除 Tooltip 组件中的这两个侦听器。是否可以在父母之前卸载孩子,或者我可以如何解决这个问题?
【问题讨论】:
-
当我点击按钮时 - 点击会发生什么?尚不清楚为什么会触发 componentWillUnmount。请提供stackoverflow.com/help/mcve
-
@estus 我添加了更多详细信息,例如 onClick 事件的作用
-
我不确定例如我得到的按钮只为某些组件设置新状态,然后将呈现简单的 div 是什么意思。是否呈现 div 而不是 Button 和 Tooltip?
标签: javascript reactjs