1. 程式人生 > >reactjs--實現switch按鈕元件(並監聽狀態)

reactjs--實現switch按鈕元件(並監聽狀態)

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、效果圖