Radio Input onChange只发射一次? [英] Radio Input onChange only fires once?

查看:66
本文介绍了Radio Input onChange只发射一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想要完成的简单任务:只要在其组之间切换一个单选按钮就触发一个函数。

I have a simple task I'm trying to accomplish: Fire a function whenever a radio button is toggled between its group.

class App extends Component {
    onButtonClick() {
        console.log('something was clicked!')
    }

    return (
      <div>
        <button onClick={this.onButtonClick.bind(this)}>
            Click me
        </button>
        <input
            type="checkbox"
            onChange={this.onButtonClick.bind(this)}
        />
        <input
            type="radio"
            value="yes"
            name="answer"
            onChange={this.onButtonClick.bind(this)}
        />
        <input
            type="radio"
            value="no"
            name="answer"
            onChange={this.onButtonClick.bind(this)}
        />
      </div>
    )
}

按钮和复选框工作正常。如果单击它,它会多次触发该函数。单选按钮触发一次然后停止。

The button and checkbox work just fine. If you click on it, it fires the function multiple times. The radio buttons fire once and then stop.

这几乎就像ReactJS由于某种原因停止观看onChange单选按钮一样。任何帮助将不胜感激。谢谢!

It's almost as if ReactJS stops watching for the onChange for radio buttons for some reason. Any help would be greatly appreciated. Thank you!

UPDATE

好像它在 https://codesandbox.io/s/rGMGzJNL ,但在我的本地环境中无法正常工作,这完全令人困惑。如果我弄清楚发生了什么会更新,但如果有人遇到过这个问题,我会很感激任何指导!

It seems like it works properly in https://codesandbox.io/s/rGMGzJNL, but is not working properly in my local environment which is utterly perplexing. Will update if I figure out what is going on, but would appreciate any guidance if anyone has run into this before!

推荐答案

你需要在每个无线电上设置已检查属性并将无线电状态保存在状态。

You need to set checked property on each radio and save radio status in state.

class App extends Component {
  state = {
    radio: 'yes',
  }

  onButtonClick() {
    console.log("something was clicked!");
  }

  onRadioChange(value) {
    console.log("radio change");
    this.setState({
      radio: value,
    })
  }

  render() {
    return (
      <div>
        <button onClick={() => this.onButtonClick()}>
          Click me
        </button>
        <input type="checkbox" onClick={() => this.onButtonClick()} />
        <input
          type="radio"
          value="yes"
          name="answer"
          checked={this.state.radio === 'yes'}
          onChange={(e) => this.onRadioChange('yes')}
        />
        <input
          type="radio"
          value="no"
          name="answer"
          checked={this.state.radio === 'no'}
          onChange={(e) => this.onRadioChange('no')}
        />
      </div>
    );
  }
}

这篇关于Radio Input onChange只发射一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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