import React from 'react';

const css_div_parent = {
display: 'inline-block',
position: 'relative',
width: '2rem',
height: '1rem',
top: '.24rem',
left: '.9rem',
backgroundColor: 'rgb(158,227,251)',
border: '1px solid rgb(158,227,251)',
borderRadius: '.5rem',
transition: 'background-color .2s linear,border-color .2s linear'
};

const css_div_child = {
position: 'absolute',
width: '1rem',
height: '1rem',
backgroundColor: 'rgb(255,223,109)',
borderRadius: '50%',
boxShadow: '1px 1px 8px #888',
transition: 'transform .2s linear'
};

//开关按钮组件
class ToggleButton extends React.Component {
constructor(props) {
super(props);

let value = this.props.value;


this.div_parent = React.createRef();
this.div_child = React.createRef();

this.state = {
value: value
};

this.handleClick = this.handleClick.bind(this);
}

componentDidMount() {
this.setStyle(this.state.value);
}

setStyle(v){
if(v){
this.div_parent.current.style.backgroundColor = 'rgb(158,227,251)';
this.div_parent.current.style.borderColor = 'rgb(158,227,251)';
this.div_child.current.style.transform = 'translateX(1rem)';
}
else{
this.div_parent.current.style.backgroundColor = 'white';
this.div_parent.current.style.borderColor = '#ddd';
this.div_child.current.style.transform = 'translateX(0rem)';
}
}

handleClick(){
this.setState(state => ({
value: !state.value
}),()=>{
this.setStyle(this.state.value);
this.props.onClick(this.state.value);
});
}

render() {
return (
<div onClick={this.handleClick} style={css_div_parent} ref={this.div_parent}>
<div style={css_div_child} ref={this.div_child}></div>
</div>
);
}
}

export default ToggleButton;