对于使用 Reux 的 React 中的组件,如何在一种情况下不触发鼠标事件以及如何在另一种情况下触发鼠标事件

For a component in React with Reux, how to not fire mouse event in one case and how to fire mouse event in another case

我有一个 Photo 组件,它看起来像这样:

class Photo extends Component {
    mouseEnter() {
        //some actions
    }

    render() {
        <img src={this.props.src} onMouseEnter={::this.mouseEnter}>
    }
}

Photo 在其他组件中重复使用。在某些组件中,我想触发 PhotoonMouseEnter 事件,但在其他一些组件中,我不想触发 onMouseEnter 事件。

class ComponentA extends Component {
    render() {
        <Photo {...this.props}></Photo>
        //want to fire mouse enter event of Photo
    }
}

class ComponentB extends Component {
    render() {
        <Photo {...this.props}></Photo>
        //want to not fire mouse enter event of Photo
    }
}

如何实现?谢谢

您可以像 hireMouseEvent 添加一个新道具并将其传递给 <Photo>

mouseEnter() {
    if(this.props.hireMouseEvent) {
    }
}

在渲染组件时添加它

<Photo hireMouseEvent={false}></Photo>

在 React 中,props 作为没有值的属性传递到您的组件中,并作为 true 布尔值传递。例如 <Photo useMouseEnter /> 会给你 this.props.useMouseEnter === true。使用这个你可以控制是否使用 mouseEnter

class Photo extends Component {
    mouseEnter() {
        //some actions
    }

    render() {
        <img
            src={this.props.src} 
            onMouseEnter={this.props.useMouseEnter ?
                this.mouseEnter : null}
        >
    }
}

如果 this.props.useMouseEnter 存在,则 onMouseEnter 中的旋转操作将通过 this.mouseEnter,否则 null

尝试以下操作。不要忘记将 onMouseEnter 绑定到照片 class。

当您想从 Photo 组件接收事件时,将 onMouseEnter 处理程序传递给 Photo 组件。

class Photo extends React.Component {
 onMouseEnter = evt => {
  !this.props.onMouseEnter && this.props.onMouseEnter(evt)
 }

 render() {
  return (
   <img
    src={this.props.src}
    onMouseEnter={this.onMouseEnter}
   />
  )
 }
}