使用react怎么实现一个Radio组件?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
测试组件:
class Test extends Component {
constructor(props) {
super(props)
this.state = {
active:1
}
}
onGroupChange(value) {
this.setState({
active: value
})
}
render() {
return (
<div>
<RadioGroup onChange={this.onGroupChange.bind(this)} active={this.state.active}>
<Radio value={1}>使用余额支付</Radio>
<Radio value={2}>使用微信支付</Radio>
</RadioGroup>
<Button onClick={()=>{
console.log("此时选中的是:"+this.state.active)
}}>下一步</Button>
</div>
)
}
}
export default Test;
RadioGroup:
import React, { Component } from 'react';
class RadioGroup extends Component {
handleActiveChange(value) {
console.log(`${value}被选中了`)
this.props.onChange(value)
}
render() {
return (
<div>
{
React.Children.map(this.props.children, child => {
let isActive = this.props.active === child.props.value ? true : false
return React.cloneElement(child, {
label: child.props.children,
value: child.props.value,
active: isActive,
onClick: this.handleActiveChange.bind(this)
})
})
}
</div>
)
}
}
export default RadioGroup;
Radio.jsx:
import React, { Component } from 'react';
import "./radio.scss"
class Radio extends Component {
render() {
return (
<div className="radio-wrap" onClick={this.props.onClick.bind(this,this.props.value)}>
<div className="left">
<div className={`circle ${this.props.active === true ? 'active' : ''} `}>
<div className="fork"></div>
</div>
<div className="label">{this.props.label}</div>
</div>
</div>
)
}
}
export default Radio;
Radio.scss:
.radio-wrap {
height: 40px;
background-color: #ffffff;
display: flex;
align-items: center;
padding: 0px 30px;
&:active {
background-color: rgb(221, 221, 221);
}
.left {
display: inline-block;
.circle {
display: inline-block;
height: 22px;
width: 22px;
box-sizing: border-box;
border: 1px solid #c5c9cd;
border-radius: 50%;
background-color: #ffffff;
position: relative;
}
.active{
background-color: #1eb94a;
.fork {
height: 12px;
width: 5px;
border-right: 1.5px solid #ffffff;
border-bottom: 1.5px solid #ffffff;
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%) rotate(45deg);
}
}
.label {
vertical-align: top;
margin-left: 10px;
display: inline-block;
height: 22px;
line-height: 22px;
font-size: 14px;
}
}
}
关于使用react怎么实现一个Radio组件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。