实现:
单选框不能设置样式,所以使用div包裹并设置两个div绝对定位覆盖在单选框上,并使得div层级降低,使得能够响应单选框的onChange事件
第一个div为未点击时样式,第二个div为点击样式
通过动态添加类名等实现传递参数改变样式
使用:
参数
label:Proptypes.string, 单选框标签
color:Proptypes.string, 单选框颜色
size:Proptypes.string, 单选框大小
values:Proptypes.array, 单选框内容数组,会根据数组内容自动生成单选框
onChange:Proptypes.func, 点击回调,第一个参数为点击单选框的索引
disabled:Proptypes.any 是否禁用
代码示例:
效果图:
禁用:
实现:
import React,{Component} from 'react'
import Proptypes from 'prop-types'
import './index.css'
class App extends Component{
static propTypes={
label:Proptypes.string,
disabled:Proptypes.bool,
color:Proptypes.string,
size:Proptypes.string,
values:Proptypes.array,
onChange:Proptypes.func,
disabled:Proptypes.any
}
static defaultProps={
color:"green",
size:'16px',
values:['内容1','内容2']
}
state={
currentIndex:-1,
className:['jf-radio']
}
componentDidMount()
{
}
_onChange(e,index)
{
let className=this.state.className;
this.setState({
currentIndex:index,
className:this.state.className
})
this.props.onChange(index);
}
render()
{
const {currentIndex,className} = this.state;
const {color,size,values,disabled} = this.props;
return(
<div className='jf-container'>
{
values.map((item,index)=>{
return (
<div className={`${disabled&&'jf-disabled'} jf-item`} key={item}>
<div style={{width:size,height:size}} className='jf'>
{index==currentIndex&&<div style={{backgroundColor:color}} className='jf-checked'></div>}
<div className={className.join(" ")}></div>
<input id={item} style={{width:size,height:size}} onChange={disabled?function(){}:(e)=>{this._onChange(e,index)}} name='one' className={`${disabled&&'jf-disabled-radio'} radio`} aria-hidden="true" type="radio"/>
</div>
<label htmlFor={item} style={{lineHeight:size,cursor:disabled?'not-allowed':'pointer'}}>{item}</label>
</div>
)
})
}
</div>
)
}
}
export default App
css:
.radio{
width: 20px;
height: 20px;
opacity: 0;
cursor: pointer;
}
.jf-container{
display:flex;
}
.jf-item{
display:flex;
align-items:'center';
margin: 10px 10px;
cursor: pointer;
}
.jf{
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 20px;
width: 20px;
border-radius: 100%;
cursor: pointer;
}
.jf-radio{
position: absolute;
background-color: white;
border:solid 1px #ccc;
border-radius: 50%;
left: 0;
bottom: 0;
right: 0;
top: 0;
z-index: -1;
cursor: pointer;
}
.jf-checked{
position: absolute;
background-color: red;
border-radius: 50%;
left: 0;
bottom: 0;
right: 0;
top: 0;
}
.jf-disabled{
cursor: not-allowed;
opacity: 0.4;
}
.jf-disabled-radio{
cursor: not-allowed;
opacity: 0;
}
使用:
{/* disabled */}
<Radio color={"pink"} size="18px" values={['内容1','内容2']} onChange={this._onChange.bind(this)}></Radio>