1

我正在尝试使用 react-toolbox 单选按钮https://github.com/react-toolbox/react-toolbox/tree/dev/components/radio在我的反应应用程序中设置单选按钮。

这是我的代码:

import {RadioGroup, RadioButton} from 'react-toolbox/lib/radio';

class ClientsEdit extends Component {
    constructor(props) {
        super(props);
        this.bindLibs();

        this.state = {
            counterType: 1
        };
    }

   // Some other functions

    render() {
        return (
            <div>
                 <RadioGroup name='counterType' value={this.state.counterType} onChange={this.handleRadioButtonChange}>
                    <RadioButton label={t('clients:new.numeric')} value={1}/>
                    <RadioButton label={t('clients:new.alphanumeric')} value={2}/>
                 </RadioGroup>
            </div>
        );
    }

    bindLibs= () => {
    // ...
        this.handleRadioButtonChange = handleRadioButtonChange.bind(this);
    }
}

有两个问题:

  1. 尽管我声明 this.state.counterType为 1,但未检查单选按钮
  2. 尝试更改状态(通过单击)时,不会触发 onChange

使用字符串而不是整数也不能解决问题。我在这里做错了什么?谢谢!

4

2 回答 2

1

您应该使用string而不是numberinvalue

import React,{Component} from 'react';
import {RadioGroup, RadioButton} from 'react-toolbox/lib/radio';

class ClientsEdit extends Component {
    constructor(props) {
        super(props);
        this.handleRadioButtonChange = this.handleRadioButtonChange.bind(this);
        this.state = {
            counterType: '1' // changed
        };
    }

    handleRadioButtonChange(e){
       this.setState({
       counterType:e
     })
    }
    render() {
        return (
            <div>
                 <RadioGroup name='counterType' value={this.state.counterType} onChange={this.handleRadioButtonChange}>
                    <RadioButton label={'first'} value={'1'}/>  // changed
                    <RadioButton label={'last'} value={'2'}/>    // changed
                 </RadioGroup>
            </div>
        );
    }

}

export default ClientsEdit

检查此在线片段链接

于 2017-08-01T13:58:48.873 回答
1

据我所知,由于您没有在您的状态下设置“值”,因此它不会检查任何单选按钮。另外,由于您没有指定“handleRadioButtonChange”,我建议您在当前组件中像这样定义它

handleRadioButtonChange = (value) => {
  this.setState({value});
};

在此处查看自述文件中给出的示例:https ://github.com/react-toolbox/react-toolbox/tree/dev/components/radio

于 2017-08-01T13:51:33.337 回答