reactjs--实现switch按钮组件(并监听状态)

来源:互联网 发布:javascript初级教程 编辑:程序博客网 时间:2024/04/30 08:33

1、首先引入相关js

<script src="js/react.js"></script><script src="js/react-dom.js"></script><script src="js/browser.min.js"></script><script src="js/jquery.min.js"></script>

2、实现switch按钮的css

.switch{   display:none;}label{   position:relative;   display: block;   border-radius: 24px;   width:100px;   height: 40px;   border:2px solid green;   cursor: pointer;}label:before{   content: '开启';   line-height:36px;   text-indent: 50px;   color:green;   display: block;   border-radius: 20px;   height: 36px;   -webkit-transition: all 0.3s ease;}label:after{   content: '';   position: absolute;   top:0;   left:1px;   width: 37px;   height: 37px;   border-radius: 50%;   background-color: #fff;   box-shadow: 1px 1px 1px 1px rgba(0,0,0,0.08);   -webkit-transition: all 0.3s ease;}.switch:checked~label:after{   margin-left: 60px;}.switch:checked~label:before{   background-color:green;   content: '关闭';   text-indent: 10px;   color:#fff;}

3、reactjs组件代码

<div id="toggle"></div><script type="text/babel">    //切换按钮    var ToggleButton = React.createClass({        getInitialState:function(){            return {                isChecked:true            };        },        btnClick:function(){            console.log(this.state.isChecked);            this.setState({                isChecked: !this.state.isChecked            });        },        render: function(){            return (                    <div className="switch-cont" onClick={this.btnClick}>                        {this.state.isChecked?                        <input id="checked_2" type="checkbox" className="switch" checked/>:                        <input id="checked_2" type="checkbox" className="switch" />                        }                        <label for="checked_2"></label>                    </div>            );        }    });    ReactDOM.render(            <ToggleButton  />,            document.getElementById('toggle')    );</script>

4、效果图

0 0
原创粉丝点击