简体   繁体   中英

setState is not working with multiple onClick function

I have weird issue, and been trying to debug for hours, still can't not find out why. I have a button onClick, to handle other 2 function, some weird reason the setState one wouldn't work if I have 2 function, if I just keep one function, setState will work, but I need both function.

Here's my code (And when I reproduce the issue here, it seems work, but the sample it's not update API, it's just change the state)

Thank you for the help!

class RecipeReviewCard extends React.Component {
  constructor(props) {
    super();
    this.state = {
      expanded: false,
      in: false,
      text: false
    };
  }

  handleClick = () => {
    this.setState(state => ({ expanded: !state.expanded }));
  };
   /* If I comment out this one, first setState will work */
  handleClick = e => {
    this.setState({ in: !this.state.in });
   /* This come from parent props to update API */
    this.props.updateThing(e.target.value)
  };
<Button
   className={classes.button}
   onClick={e => this.handleClick()}
>

In your constructor, you should call super(props); see: https://overreacted.io/why-do-we-write-super-props/

In your Button - you are not passing the event object to your event handler.

<Button
   className={classes.button}
   onClick={e => this.handleClick(e)} // note the e here.
>

Since your handleClick function is already bound to your component instance, you should just provide it to onClick handler directly without writing that arrow function, like so:

<Button
   className={classes.button}
   onClick={this.handleClick}
>

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