简体   繁体   English

如何处理两个函数 onClick

[英]How to handle two functions onClick

In my Class component App.jsx I have the following function:在我的 Class 组件App.jsx我有以下功能:

import { Position } from "./Position";
...

getPositionData = val => {
    const { players } = this.props;       
    var res = players.filter(o=>Object.values(o).includes(val))        
    return res
  };

Which is being handled at render() when I click on a subcomponent inside a <div> , like so:当我单击<div>内的子组件时,它正在render()处理,如下所示:

<div className="field-row"> 
   {this.getPlayersByPosition(players, 4).map((player,i) => (
      <Position key={i} handleClick={this.getPositionData}>{player.name}</Position>
    ))} 
</div>

On its turn, Position.jsx handles onClick() :轮到Position.jsx处理onClick()

export const Position = props => (
  <div
    className={`position-wrapper ${
      isManager(props.children) ? null : "field"
    }`}
    onClick={() => props.handleClick(props.children)}
  >
    {props.children}
  </div>
);

But now I'd like to handle a second function when <div> is clicked, say:但是现在我想在单击<div>时处理第二个函数,例如:

 toggleFullScreen() {
    this.setState({ fullScreen: !this.state.fullScreen });
  }

which I would pass, on its own, like so:我会自己通过,就像这样:

onClick={this.toggleFullScreen.bind(this)}

How do I handle BOTH functions onClick() at once in我如何同时处理onClick()两个函数

<div className="field-row"> 
...
</div>

? ?

Just like you can invoke multiple functions at once in a JS listener with就像您可以在 JS 侦听器中一次调用多个函数一样

element.addEventListener('click', () => {
  fn1();
  fn2();
});

You can do the same thing in React by defining the onClick to be a function which invokes both:你可以在 React 中做同样的事情,方法是将onClick定义为一个调用两者的函数:

<Position
  key={i}
  getPositionData={this.getPositionData}
  toggleFullScreen={toggleFullScreen}
>{player.name}</Position>
export const Position = props => (
  <div
    className={`position-wrapper ${
      isManager(props.children) ? null : "field"
    }`}
    onClick={() => {
      props.getPositionData(props.children);
      props.toggleFullScreen();
    }}
  >
    {props.children}
  </div>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM