我正在使用React.js构建我的组件库。出于某些原因,我不想使用CSS进行样式设计。而不是它,我使用JSON符号样式,如
{
"some-class": {
"color": "#755755"
},
"some-class:hover": {
"background": "#CCC"
}
}
通过deisgn,React建议尽可能保持组件无状态,但对于:hover
或:active
这样的条件,我使用onMouseOver
和onMouseOut
:
/**
* Mouse over handler
* @return {Void}
*/
onMouseOver: function() {
this.setState({
style: extend(
{},
this.state.style,
style['mdui-btn-' + this.props.type + ':hover']
)
});
},
/**
* Mouse out handler
* @return {Void}
*/
onMouseOut: function() {
this.setState({
style: this.computeStyle()
});
},
我认为如果我想避免使用CSS,我可以使用这种行为。是不是坏主意?
答案 0 :(得分:2)
我发现这是一种处理组件悬停样式更改的简洁方法:
var SomeComponent = React.createClass({
getInitialState: function(){
return {hovered: false};
},
toggleHovered: function(){
this.setState({hovered: !this.state.hovered});
}
render: function(){
//example for rendering a span with desired hovering functionality
return(
<span style={this.state.hovered ? myStyles.hoverOn : myStyles.hoverOff} onMouseOver={this.toggleHovered}> onMouseOut={this.toggleHovered}>
Some content
</span>
);
}
});
var myStyles = {
hoverOn: {
// whatever styles you want on hover
},
hoverOff: {
// style for no hover
}
};