如何在一个div上调用多个事件处理程序



我有一个图标,显示一个弹出的div当用户悬停在它或专注于它,然后消失时,用户的鼠标移出或模糊。目前我有这个:

<div
className="iconWrapper"
onFocus={() => this.showToolTip(true)}
onBlur={() => this.showToolTip(false)}
onMouseOver={() => this.showToolTip(true)}
onMouseOut={() => this.showToolTip(false)}
tabIndex="0"
role="button">
<Icon width="12" height="12" fillColor="#000" />
</div>

这是有效的,但它相当混乱,有没有其他方法来完成这个目标?

这取决于你想记住多少。

如果你根本不想记忆,你至少可以避免创建多个相同的函数:

const showToolTip = () => this.showToolTip(true);
const hideToolTip = () => this.showToolTip(false);
return (
<div
className="iconWrapper"
onFocus={showToolTip}
onBlur={hideToolTip}
onMouseOver={showToolTip}
onMouseOut={hideToolTip}
tabIndex="0"
role="button"
>
<Icon width="12" height="12" fillColor="#000" />
</div>
);

或者你可以在构造函数中创建这些函数:

constructor(props) {
super(props);
// ***NOTE** I renamed your original instance method from `showToolTip` to
// `updateToolTip` so I could use `showToolTip` for the one that specifically
// *shows* it
this.showToolTip = () => this.updateToolTip(true);
this.hideToolTip = () => this.updateToolTip(false);
}

…然后在渲染中重用它们:

return (
<div
className="iconWrapper"
onFocus={this.showToolTip}
onBlur={this.hideToolTip}
onMouseOver={this.showToolTip}
onMouseOut={this.hideToolTip}
tabIndex="0"
role="button"
>
<Icon width="12" height="12" fillColor="#000" />
</div>
);

这样做的好处是,它使您的事件处理程序函数在整个渲染中稳定。这对div来说并不重要,但如果你使用shouldComponentUpdateclass组件提供这些功能,或者使用React.memo为功能组件提供这些功能来优化渲染,那么让它们保持稳定可以节省子组件渲染。

我想到的另一个选择是创建handlers对象并在组件上使用扩展语法:

const toolTipHandlers = { 
onFocus: () => this.showToolTip(true),
onBlur: () => this.showToolTip(false),
onMouseOver: () => this.showToolTip(true),
onMouseOut: () => this.showToolTip(false),
};
return(
<div
{...toolTipHandlers}
className="iconWrapper"
tabIndex="0"
role="button"
>
<Icon width="12" height="12" fillColor="#000" />
</div>);

最新更新