UNPKG

2.74 kBJavaScriptView Raw
1import classnames from 'classnames';
2import React from 'react';
3import PropTypes from 'prop-types';
4
5
6const propTypes = {
7 /**
8 * radio 颜色 样式
9 */
10 colors: PropTypes.oneOf(['', 'dark', 'success', 'info', 'warning', 'danger','primary']),
11 /**
12 * radio 大小
13 */
14 size: PropTypes.oneOf(['lg','sm']),
15 /**
16 * radio 是否可用
17 */
18 disabled: PropTypes.bool,
19 /**
20 * radio 样式 是否使用红色填充
21 */
22 inverse: PropTypes.bool
23};
24
25const defaultProps = {
26 inverse: false,
27 disabled: false,
28 clsPrefix: 'u-radio'
29};
30
31/**
32 * 建立与RadioGroup通信
33 */
34const contextTypes = {
35 radioGroup: PropTypes.object
36}
37
38
39class Radio extends React.Component {
40 constructor(props, context) {
41
42 super(props, context);
43
44 this.handleClick = this.handleClick.bind(this);
45
46 }
47
48 handleClick(event) {
49 const {onChange } = this.context.radioGroup;
50 if (this.props.disabled) {
51 return;
52 }
53 if (onChange) {
54 onChange(this.props.value);
55 }
56 }
57
58 render() {
59 const {name, selectedValue,size,focusvalue} = this.context.radioGroup;
60 /**
61 * 自身的属性
62 */
63 const {
64 inverse,
65 disabled,
66 colors,
67 className,
68 children,
69 clsPrefix,
70 style,
71 ...others
72 } = this.props;
73
74 let optional = {};
75 /**
76 * 若父级selectedValue与本身的value值相同,则改radio被选中
77 */
78 if(selectedValue !== undefined) {
79 optional.checked = (this.props.value === selectedValue);
80 }
81
82 let classes = {
83 'is-checked':optional.checked,
84 disabled
85 };
86
87 if (colors) {
88 classes[`${clsPrefix}-${colors}`] = true;
89 }
90 if (size) {
91 classes[`${clsPrefix}-${size}`] = true;
92 }
93 if (inverse) {
94 classes[`${clsPrefix}-inverse`] = true;
95 }
96 if (children == null) {
97 classes[`${clsPrefix}-noContent`] = true;
98 }
99 let classNames = classnames(clsPrefix,classes);
100 let tabIndex=optional.checked?0:-1;
101 if(focusvalue&&focusvalue==this.props.value){
102 tabIndex = 0 ;
103 }
104 const input = (
105 <input
106 {...others}
107 type="radio"
108 name={name}
109 disabled={this.props.disabled}
110 tabIndex={tabIndex}
111 />
112 );
113 return (
114 <label style={style} onClick = {this.handleClick} className={classnames(className, classNames)}>
115 {input}
116 <label className={clsPrefix+'-label'}>{children}</label>
117 </label>
118 );
119
120 }
121}
122
123Radio.contextTypes = contextTypes;
124Radio.propTypes = propTypes;
125Radio.defaultProps = defaultProps;
126
127export default Radio;