ReactJS 组件 - RadioGroup组件
2017-01-23 本文已影响2362人
void_main
radio组件的使用方法
this.state = {
selectedValue : 'PC'
}
handleChange(event){
console.log('change');
console.log(event);
this.setState({selectedValue:event});
}
<RadioGroup name="platform" selectedValue={this.state.selectedValue} onChange={(event)=>{this.handleChange(event)}}>
<Radio value="PC" disabled="true">PC</Radio>
<Radio value="APP">APP</Radio>
<Radio value="WAP">WAP</Radio>
</RadioGroup>
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 (
<span className="normal-radio">
<input type="radio" name={name} {...optional} className="radio-input"/>
<i className="box"></i>{children}
</span>
);
}
}
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 (<Component {...rest}>{children}</Component>) ;
}
}
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}