React Checkbox不发送onChange

jda*_*ing 105 checkbox onchange reactjs

TLDR:使用defaultChecked而不是checked,在这里工作jsbin http://jsbin.com/mecimayawe/1/edit?js,output

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

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>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

用法:

React.renderComponent(CrossoutCheckbox({text: "Text Text", complete: false}), mountNode);
Run Code Online (Sandbox Code Playgroud)

解:

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

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>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

zby*_*yte 168

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

this.refs.complete.state.checked
Run Code Online (Sandbox Code Playgroud)

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

event.target.checked
Run Code Online (Sandbox Code Playgroud)

  • 尝试在输入中使用defaultChecked = {this.state.complete}而不是"checked". (11认同)
  • handleChange永远不会被调用,如果单击复选框或标签无关紧要,handleChange不会被调用:(. (3认同)
  • 设置`checked`表示在组件外部管理状态.当用户点击时,没有任何东西可以调用`handleChange`,因为没有更新状态.相反,你需要监听`onClick`并在那里触发状态更新. (3认同)

Lin*_*Lin 18

在这种情况下最好不要使用refs.使用:

<input
    type="checkbox"
    checked={this.state.active}
    onClick={this.handleClick}
/>
Run Code Online (Sandbox Code Playgroud)

有一些选择:

checked VS defaultChecked

前者将响应状态变化点击.后者会忽略状态变化.

onClick VS onChange

前者总是会触发点击.如果元素checked上存在属性,则后者不会触发点击input.

  • 我正在使用 React 16.13.1,如果没有 onChange 属性,则无法提供选中的属性。如果我定义两者,并使选中的属性响应输入,那么每次单击该框时我都会得到所需的行为和 onChange 触发器。所以我认为这个答案已经过时了。 (4认同)

aki*_*enc 9

在场景中,您不希望在输入DOM上使用onChange处理程序,您可以使用该onClick属性作为替代.的defaultChecked,条件可离开V16 IINM固定状态.

 class CrossOutCheckbox extends Component {
      constructor(init){
          super(init);
          this.handleChange = this.handleChange.bind(this);
      }
      handleChange({target}){
          if (target.checked){
             target.removeAttribute('checked');
             target.parentNode.style.textDecoration = "";
          } else {
             target.setAttribute('checked', true);
             target.parentNode.style.textDecoration = "line-through";
          }
      }
      render(){
         return (
            <span>
              <label style={{textDecoration: this.props.complete?"line-through":""}}>
                 <input type="checkbox"
                        onClick={this.handleChange}
                        defaultChecked={this.props.complete}
                  />
              </label>
                {this.props.text}
            </span>
        )
    }
 }
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助将来的某个人.


Paw*_*ski 8

如果有人正在寻找通用事件处理程序,可以或多或少地使用以下代码(假设为每个输入设置了name属性):

    this.handleInputChange = (e) => {
        item[e.target.name] = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    }
Run Code Online (Sandbox Code Playgroud)


spe*_*.sm 6

如果您具有如下所示的handleChange函数:

handleChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value,
  });
}
Run Code Online (Sandbox Code Playgroud)

您可以创建一个自定义onChange函数,使其像文本输入一样:

<input
  type="checkbox"
  name="check"
  checked={this.state.check}
  onChange={(e) => {
    this.handleChange({
      target: {
        name: e.target.name,
        value: e.target.checked,
      },
    });
  }}
/>
Run Code Online (Sandbox Code Playgroud)

  • @Haikel,如果您有一个仅处理复选框输入的handleChange函数,那么这是正确的,但是如果您注意到在第二个代码块中,我们在箭头函数中调用“handleChange”并将“target.value”设置为“ e.target.checked`(本质上是创建一个人造事件)。这样做是为了使相同的handleChange函数也可以用于文本输入,因为这就是它们在更改事件中传递值的方式。 (3认同)