通过单选按钮选择调用 onChange 功能

IT技术 reactjs
2021-05-23 05:26:52

我想使用单选按钮来使用双按钮切换来注册状态值(我将使用它来处理用户在点击提交按钮后将采取的路线)。

var Pathfinder = React.createClass({
  getInitialState: function() {
    return {query: '', pathname: '', route: 'one'};
  },
  handleRadioButton: function(type) {
    console.log('type: ', type);
    this.setState({route: type});
  },
  handleTextField: function(event) {
    if (this.state.route === 'one') {
      this.setState({pathname: '/pathone/'});
    } else {
      this.setState({pathname: '/pathtwo/'});
    }
  },
  render: function() {
    return (
      <div>
        <div>
          <div>
            <input autoFocus type="search" onChange={this.handleTextField} />
            <div>
              <Link to={this.state.pathname}>
                <button type="submit"><i className="glyphicon glyphicon-search"></i></button>
              </Link>
            </div>
            <div data-toggle="buttons">
              <label>
                <input type="radio" checked={this.state.route === 'one'} onChange={() => this.handleRadioButton('one')} />1
              </label>
              <label>
                <input type="radio" checked={this.state.route === 'two'} onChange={() => this.handleRadioButton('two')} />2
              </label>
            </div>
          </div>
        </div>
      </div>
      );
  }
});

如上运行,该onChange函数永远不会被调用。

如果我将onChange匿名函数更改为: onChange={setTimeout( () => this.handleRadioButton('one'), 0)}那么它只是快速地从onetwo无限地来回变化

1个回答

我没有提到我正在使用 Bootstrap,因为我认为它不相关……但它显然是。当涉及某些输入类型时,React 和 Bootstrap 之间存在冲突,包括单选按钮。

切换到react-bootstrap它现在渲染得很好 - 只需要修复一些样式。