反应复选框不发送 onChange [英] React Checkbox not sending onChange

查看:20
本文介绍了反应复选框不发送 onChange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TLDR:使用 defaultChecked 而不是检查,工作 jsbin.

TLDR: Use defaultChecked instead of checked, working jsbin.

尝试设置一个简单的复选框,当它被选中时会划掉它的标签文本.出于某种原因,当我使用该组件时,handleChange 不会被触发.谁能解释一下我做错了什么?

Trying to setup a simple checkbox that will cross out its label text when it is checked. For some reason handleChange is not getting fired when I use the component. Can anyone explain what I'm doing wrong?

var CrossoutCheckbox = React.createClass({
  getInitialState: function () {
    return {
        complete: (!!this.props.complete) || false
      };
  },
  handleChange: function(){
    console.log('handleChange', this.refs.complete.checked); // Never gets logged
    this.setState({
      complete: this.refs.complete.checked
    });
  },
  render: function(){
    var labelStyle={
      'text-decoration': this.state.complete?'line-through':''
    };
    return (
      <span>
        <label style={labelStyle}>
          <input
            type="checkbox"
            checked={this.state.complete}
            ref="complete"
            onChange={this.handleChange}
          />
          {this.props.text}
        </label>
      </span>
    );
  }
});

用法:

React.renderComponent(CrossoutCheckbox({text: "Text Text", complete: false}), mountNode);

解决方案:

使用 checked 不会让底层值改变(显然),因此不会调用 onChange 处理程序.切换到 defaultChecked 似乎可以解决这个问题:

Using checked doesn't let the underlying value change (apparently) and thus doesn't call the onChange handler. Switching to defaultChecked seems to fix this:

var CrossoutCheckbox = React.createClass({
  getInitialState: function () {
    return {
        complete: (!!this.props.complete) || false
      };
  },
  handleChange: function(){
    this.setState({
      complete: !this.state.complete
    });
  },
  render: function(){
    var labelStyle={
      'text-decoration': this.state.complete?'line-through':''
    };
    return (
      <span>
        <label style={labelStyle}>
          <input
            type="checkbox"
            defaultChecked={this.state.complete}
            ref="complete"
            onChange={this.handleChange}
          />
          {this.props.text}
        </label>
      </span>
    );
  }
});

推荐答案

要获取复选框的选中状态,路径为:

To get the checked state of your checkbox the path would be:

this.refs.complete.state.checked

另一种方法是从传递给 handleChange 方法的事件中获取它:

The alternative is to get it from the event passed into the handleChange method:

event.target.checked

这篇关于反应复选框不发送 onChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆