简体   繁体   English

在 react-bootstrap 按钮中将多个操作传递给 onClick 事件

[英]Passing multiple actions to onClick event in a react-bootstrap Button

Consider a react/redux application with react-bootstrap components.考虑一个带有 react-bootstrap 组件的 react/redux 应用程序。

This may be a very rookie question, but I am trying to pass multiple actions to a single onClick event on a Button from a react-bootstrap library.这可能是一个非常新手的问题,但我试图将多个操作传递给来自 react-bootstrap 库的 Button 上的单个 onClick 事件。

<Button bsStyle="success" bsSize="small" onClick={someCallback; someOtherCallback;}>
  Something
</Button>

How to do this properly?如何正确执行此操作?

Wrap them in another function:将它们包装在另一个函数中:

<Button bsStyle="success" bsSize="small" onClick={onButtonClick}>
  Something
</Button>
...
onButtonClick = function(event){
  someCallback()
  someOtherCallback()
}

You can use the following code to do more than one thing when the button is fired当按钮被触发时,您可以使用以下代码做不止一件事

 function doMagic { //do something //do another thing }
 <Button bsStyle="success" bsSize="small" onClick="doMagic()"> Something </Button>

I had a similar issue with my application (using React JS + Bootstrap 5).我的应用程序也有类似的问题(使用 React JS + Bootstrap 5)。 I wanted to use onClick to call an API (searchDataRange) and also to render a section of my page (const [renderItems, setRenderItems] = useState(false);)我想使用 onClick 来调用 API (searchDataRange) 并渲染我的页面的一部分 (const [renderItems, setRenderItems] = useState(false);)

. .

I first tried this ( DID NOT WORK! ):我首先尝试了这个(没有工作! ):

 <Button type="button" 
             className="btn btn-light mx-2"
             onClick={() => setRenderItems(!renderItems); searchDataRange} </Button>

I tried a few different combos with (), {}, etc.. but this solved the issue( SOLUTION ):我用 ()、{} 等尝试了一些不同的组合。但这解决了问题(解决方案):

  const trigger = () => {
    setRenderItems(!renderItems);
    searchDateRange();
 }

return(
 <Button type="button" 
             className="btn btn-light mx-2"
             onClick={trigger}>Search</Button>
             
            </div> ...

I think there's OnClickCapture as well that works for a secondary Click Event.我认为 OnClickCapture 也适用于辅助点击事件。 Probably not the most efficient way, but I think it works in the meantime if you use Onclick for the first function and OnclickCapture for the second function.可能不是最有效的方法,但我认为如果您将Onclick用于第一个函数而OnclickCapture用于第二个函数,它会同时起作用。

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

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