我正在尝试使用CSS设计reactjs复选框组件的样式。它使用伪元素:after和:before。
在html和css上模拟一下,它就成功了!Fiddle Link
input[type="checkbox"]#checkbox + label::before {
content: "";
display: inline-block;
vertical-align: -25%;
height: 2ex;
width: 2ex;
background-color: white;
border: 1px solid #c3c4c6;
border-radius: 4px;
margin-right: 0.5em;
}
input[type="checkbox"]#checkbox:checked + label::after {
content: '';
position: absolute;
width: 1.2ex;
height: 0.4ex;
background: rgba(0, 0, 0, 0);
top: 0.5ex;
left: 0.4ex;
border: 3px solid #60cd18;
border-top: none;
border-right: none;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
transform: rotate(-45deg);
}
但当我试图在显示复选框的reactjs组件上实现它时,可能:after不起作用。Fiddle ReactJS组件链接
我应该如何在ReactJS复选框组件上实现相同的风格?
React上有几种方法可以使用伪元素,如Radium,但它不支持:after/:before,而是根据this和this,建议创建一个元素来代替伪元素。我没有找到任何React的例子,我认为伪元素的可用性是为了避免创建不必要的DOM元素。
有了所有这些限制,我目前在react中自定义复选框以使其在大多数浏览器上工作的解决方案是创建一个元素,该元素的行为、外观和感觉都像一个复选框(冒名顶替者),而不是一个本身的复选框(输入类型="checkbox")。我通过使用ReactJS来触发span元素和字体图标的可见性来实现这一点。
示例
/* html */
<div id="container">
</div>
/* JS */
var Checkbox = React.createClass({
getDefaultProps: function() {
return {
value: true,
name: '',
borderWidth: '1px',
borderStyle: 'solid',
borderColor: '#c3c4c6',
borderRadius: '4px',
checkColor: '#60cd18',
height: '1px',
width: '',
namePaddingLeft: '10px',
namePaddingRight: ''
};
},
render: function() {
var style = {
boxStyle: {
borderWidth: this.props.borderWidth,
borderStyle: this.props.borderStyle,
borderColor: this.props.borderColor,
borderRadius: this.props.borderRadius,
paddingLeft: this.props.width,
paddingRight: this.props.width,
paddingTop: this.props.height,
paddingBottom: this.props.height
},
show: {
visibility: 'visible',
color: this.props.checkColor
},
hidden: {
visibility: 'hidden',
color: this.props.checkColor
},
name: {
paddingLeft: this.props.namePaddingLeft,
paddingRight: this.props.namePaddingRight
}
};
return (
<div>
<span style={style.boxStyle}>
<i className="fa fa-check fa-lg" style={(this.props.value) ? style.show : style.hidden}></i>
</span>
<span style={style.name}>{this.props.name}</span>
</div>
);
}
});
var WrapperCheckbox = React.createClass({
getInitialState: function(){
return {value: false}
},
handleClick: function(){
console.log('Click Fires!');
this.setState({value: !this.state.value});
},
render: function(){
return (
<div onClick={this.handleClick}>
<Checkbox name='Reserve Guarantee' value={this.state.value}/>
</div>
);
}
});
React.render(<WrapperCheckbox />, document.getElementById('container'));