ReactJS 组件 - RadioGroup组件

radio组件的使用方法

this.state = {
            selectedValue : 'PC'
        }

handleChange(event){
    console.log('change');
    console.log(event);
    this.setState({selectedValue:event});
}

{this.handleChange(event)}}>
    PC
    APP
    WAP

RadioGroup具有三个属性

  • name RadioGroup的name
  • selectedValue RadioGroup数据回填的对应字段
  • onChange RadioGroup值变化是触发的函数

Radio具有两个属性

  • value 按钮选中所对应的值
  • disabled 按钮是否禁用

渲染出的DOM结构

import React, {Component, PropTypes} from 'react';
import classnames from 'classnames';
require('./index.less')

class Radio extends Component{
    render() {
        const {name, selectedValue, onChange} = this.context.radioGroup;
        const {children,disabled} = this.props;
        const optional = {};
        if(selectedValue !== undefined) {
          optional.checked = (this.props.value === selectedValue);
        }
        if(disabled !== undefined){
            optional.disabled = (this.props.disabled === disabled)        ;
        }
        if(typeof onChange === 'function') {
          optional.onChange = onChange.bind(null, this.props.value);
        }

        return (
            
                
                {children}
            
        );
    }
}

Radio.contextTypes = {
    radioGroup: React.PropTypes.object
}


class RadioGroup extends Component {
    static defaultProps = {
        Component: "div"
    }

    getChildContext() {
        const {name, selectedValue, onChange} = this.props;
        return {
            radioGroup: {
                name, selectedValue, onChange
            }
        }
    }

    render() {
        const {Component, name, selectedValue, onChange, children, ...rest} = this.props;
        return ({children}) ;
    }
}

RadioGroup.childContextTypes = {
    radioGroup: React.PropTypes.object
}

RadioGroup.propTypes = {
    name: PropTypes.string,
    selectedValue: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number,
      PropTypes.bool,
    ]),
    onChange: PropTypes.func,
    children: PropTypes.node.isRequired,
    Component: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.func,
      PropTypes.object
    ])
}

export {RadioGroup, Radio}

你可能感兴趣的:(ReactJS 组件 - RadioGroup组件)