我有一个奇怪的问题,并且尝试调试了几个小时,仍然找不到原因。 我有一个onClick按钮,用于处理其他2个函数,有些奇怪的原因是,如果我有2个函数,则setState将不起作用;如果仅保留一个函数,则setState将起作用,但是我需要两个函数。
Here's my code (当我在这里重现该问题时,它似乎可以正常工作,但是示例中它不是更新API,而只是更改状态)
谢谢您的帮助!
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()}
>
答案 0 :(得分:2)
在构造函数中,您应该调用super(props);
参见:https://overreacted.io/why-do-we-write-super-props/
在您的Button
中-您没有将事件对象传递给事件处理程序。
<Button
className={classes.button}
onClick={e => this.handleClick(e)} // note the e here.
>
由于您的handleClick
函数已经绑定到组件实例,因此您应该直接将其提供给onClick
处理程序,而无需编写该箭头函数,如下所示:
<Button
className={classes.button}
onClick={this.handleClick}
>