简体   繁体   中英

onClick has a strange behavior

I'm stuck into an issue regarding to onClick event, but first of all, I'll explain the behavior:

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. And I logged the button disabled state, and for each call seems to be enabled.

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...

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 .

In the below example console.log is added only when button is enabled. As long as button is disabled no new console.log is added. You can reset the <DisablableButton /> using Reset button.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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