简体   繁体   English

复选框 onCheck 不会触发

[英]Checkbox onCheck doesn't fire

I have a checkbox from material-ui that doesn't fire onCheck event.我有一个来自 material-ui 的复选框,它不会触发 onCheck 事件。

<Checkbox
  label="label"
  onCheck={onCheck}
  checked={currentDocument.ispublic}
/>


function onCheck() {
  currentDocument.ispublic = !currentDocument.ispublic;
  console.log("onCheck");
}

I tried removing checked property as described in this question: React Checkbox not sending onChange我尝试按照这个问题中的描述删除选中的属性: React Checkbox not sent onChange

currentDocument is an observable object stored in my store. currentDocument 是存储在我的商店中的可观察对象。

可能是因为基于https://material-ui-next.com/api/checkbox/#checkbox material-ui 暴露的是 onChange 而不是 onCheck?

Without the full content, there is no way to test your code.如果没有完整的内容,就无法测试您的代码。 But there are some possible errors:但是有一些可能的错误:

  • Where do onCheck and currentDocument come from? onCheckcurrentDocument来自哪里? If it's in the component class, you need put this keyword.如果它在组件类中,则需要放置this关键字。
  • Use arrow function for onCheck , otherwise, you can't access this without .bind(this)onCheck使用箭头函数,否则,如果没有.bind(this)就无法访问this
  • The component class should have decorator @observer and currentDocument should have @observable组件类应该有装饰器@observercurrentDocument应该有@observable

The code below is one possible answer, but I'm not sure what behavior you expected, so I didn't test.下面的代码是一种可能的答案,但我不确定您期望什么行为,因此我没有进行测试。 However, with MobX, the syntax is correct.然而,对于 MobX,语法是正确的。

@observer
class MyCheckBox extends React.Component {
  @observable currentDocument = {
    ispublic: false,
  };

  render() {
    return(
      <Checkbox
        label="label"
        onCheck={this.onCheck}
        checked={this.currentDocument.ispublic}
      />
    );
  }

  onCheck = () => {
    this.currentDocument.ispublic = !this.currentDocument.ispublic;
  }
}

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

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