React - 如何手动触发子组件的鼠标输入

React - how to manually trigger mouseenter of child component

我正在使用 ReactJS 和 Google 的 Material 组件用于使用 RMWC (https://github.com/jamesmfriedman/rmwc) 的网络。 我有一个父组件,其中包含一个图标和下面的文本。 此图标具有 Material 设计涟漪效果,这意味着当我悬停或单击它时,会触发动画。

我现在想在悬停或单击下面的文本时触发相同的效果。

组件如下:

export class Subject extends Component {
constructor(props) {
    super(props)
}

triggerRippleHover() {
    console.log("hovered");
    // HERE
  }

renderSubjectIcon(Icon) {
    return (
        <Icon className="subject-icon" />
    )
  }

render() {
    return (
        <div className="subject-container">
            <Ripple unbounded>
                <div className="subject-icon-container">
                    {this.renderSubjectIcon(this.props.icon)}
                </div>
            </Ripple>
            <span onMouseEnter={this.triggerRippleHover}>{this.props.name}</span>
        </div>
    )
}

基本上,我只想 "extend" 触发图标行为的区域(如果这有意义的话)。

我进行了广泛的搜索,但未能找到合适的答案。

非常感谢您的帮助。

您可以尝试以下方法:

1.Get <Icon /> ref 如下 (refs documented here):

<Icon className="subject-icon" ref={element => this.iconRef = element} />

2.Once 你有 <Icon /> ref,然后在你的 triggerRippleHover 回调中,你可以编程触发 mouseover 事件(或相应的)到 this.iconRefHere's another SO answer,更好地描述了如何触发事件。这是一个示例代码片段,可以让您深入了解我的想法:

triggerRippleHover() {
  // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
  const event = new MouseEvent('mouseover', {
    view: window,
    bubbles: true,
    cancelable: true
  })

  // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent  
  this.iconRef.dispatchEvent(event)
}

这里是关于如何触发事件的 MDN 文章:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

一种方法如下:

var mouseoverEvent = new Event('mouseover');

myTrigger.addEventListener("mouseover", function(){
    myMouseOver.dispatchEvent(mouseoverEvent);
});

这是完整的fiddle...https://jsfiddle.net/sarawinter79/sc2fzeqm/

非常感谢您的回答,它们很有帮助,感谢 Jordan Enev 的回答(通过触发 activate() API 涟漪效果 https://github.com/material-components/material-components-web/tree/master/packages/mdc-ripple) 但不是悬停,因为没有任何 API。

我现在意识到我需要触发 Material 组件的 :hover 伪 class,这似乎无法通过该方法实现。