简体   繁体   English

onClick 有一个奇怪的行为

[英]onClick has a strange behavior

I'm stuck into an issue regarding to onClick event, but first of all, I'll explain the behavior:我陷入了有关onClick事件的问题,但首先,我将解释行为:

I have a search bar in my app and on the results list a button that should be disabled when the search is running.我的应用程序中有一个搜索栏,结果列表中有一个在搜索运行时应禁用的按钮。 It works fine, but while the search is running and I'm clicking on that disabled button seems to add the events into a queue, and when the search is done, and the button becomes enabled, all the events are fired...它工作正常,但是当搜索正在运行并且我单击该禁用按钮时,似乎会将事件添加到队列中,并且当搜索完成并且按钮变为启用时,所有事件都会被触发......

I tried to log the event from the button onClick handler, and for example, when the button is disabled and I click 3 times on it, the handler is called 3 times at the same time after the button becomes enabled.我尝试从按钮onClick处理程序记录事件,例如,当按钮被禁用并单击 3 次时,在按钮启用后同时调用处理程序 3 次。 And I logged the button disabled state, and for each call seems to be enabled.我记录了禁用 state 的按钮,并且似乎启用了每个呼叫。

Is there a way to prevent queuing the events when the button is disabled?当按钮被禁用时,有没有办法防止事件排队? Also, when is disabled I tried to apply 'pointer-events: none' on CSS, but doesn't work...此外,当被禁用时,我尝试在 CSS 上应用“指针事件:无”,但不起作用......

return <Button 
         className={buttonClass} 
         disabled={this.props.readonly} 
         onClick={() => console.log('isReadOnly:', this.props.readonly)}
       >BUTTON TEXT</Button>

You should pass the callback () => this.setState({readonly: true}) that updates the value of readonly .您应该传递更新readonly值的回调() => this.setState({readonly: true})

In the below example console.log is added only when button is enabled.在下面的示例中, console.log仅在启用按钮时添加。 As long as button is disabled no new console.log is added.只要按钮被禁用,就不会添加新的console.log You can reset the <DisablableButton /> using Reset button.您可以使用重置按钮重置<DisablableButton />

 class App extends React.Component { constructor(props) { super(props); this.state = { readonly: false } } render() { return ( <div> <DisablableButton disabled={this.state.readonly} handleClick={() => this.setState({readonly: true})} /> <button onClick={() => this.setState({readonly: false})}>Reset</button> </div> ) } } function DisablableButton(props) { const handleClick = () => { console.log("<DisablableButton /> clicked"); props.handleClick(true); } return <button disabled={props.disabled} onClick={handleClick}>Disable</button> } ReactDOM.render(<App />, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

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

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