使用React JS创建一个自定义单选按钮 [英] Create a custom radio button using React JS

查看:502
本文介绍了使用React JS创建一个自定义单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义单选按钮.我面临的问题是,单击另一个单选按钮后,我无法取消选中该单选按钮.目前,它的行为就像一个复选框.

I'm trying to create a custom radio button. The issue that i'm facing is that i'm unable to uncheck the radio button when another radio button is clicked. Currently it behaves like a checkbox.

import {React, ReactDOM} from '../../shared/lib/react';

export default class RadioButton extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          checkedRadioBtn: false
        };
        this.toggleRadioBtn = this.toggleRadioBtn.bind(this);
     };


    toggleRadioBtn(){
        this.setState({checkedRadioBtn: !this.state.checkedRadioBtn});
    };

    render() {
        return (
            <div className="radio-btn-group">
                <div onClick={this.toggleRadioBtn} className={this.state.checkedRadioBtn ? "radiobtn checked" : "radiobtn unchecked"} data-value={this.props.value}></div>
                <label>{this.props.text}</label>
            </div>
        );
    }
};

推荐答案

您需要具有用于单选按钮组的容器.该容器将保持所有单选按钮的状态,并处理每个选项的选中/取消选中状态.这是示例代码,

You need to have container for group of radio buttons. That container will maintain the state for all the radio buttons and handle check/uncheck for each option. Here is the sample code for that,

import React from 'react'
import ReactDOM from 'react-dom'

class RadioBtn extends React.Component{

    constructor(props) {
        super(props);
    }

    handleClick(){
        this.props.handler(this.props.index);
    }

    render() {
        return (
            <div className="radio-btn-group" onClick={this.handleClick.bind(this)}>
                <div className={this.props.isChecked ? "radiobtn checked" : "radiobtn unchecked"} data-value={this.props.value}></div>
                <label>{this.props.text}</label>
            </div>
        );
    }
}

class RadioGrp extends React.Component{

    constructor() {
        super();
        this.state = {
          selectedIndex: null,
          selectedValue: null,
          options: ["option 0","option 1","option 2","option 3"]
        };
    }

    toggleRadioBtn(index){
        this.setState({
          selectedIndex: index,
          selectedValue: this.state.options[index],
          options: this.state.options
        });
    }

    render() {

        const { options } = this.state;

        const allOptions = options.map((option, i) => {
            return <RadioBtn key={i} isChecked={(this.state.selectedIndex == i)} text={option} value={option} index={i} handler={this.toggleRadioBtn.bind(this)} />
        });

        return (
            <div>{allOptions}</div>
        );
    }
}

var app = document.getElementById('app');

ReactDOM.render(<RadioGrp />, app);

这篇关于使用React JS创建一个自定义单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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