我有一个 React 组件,它实现了悬停效果,例如:
let style = {
backgroundColor: "blue"
}
class someComponent extends React.Component{
constructor(props){
super(props)
this.state = {
hover: false
}
}
handleHover(event) {
this.setState({ hover: true });
}
handleExit(event) {
this.setState({ hover: false });
}
render(){
if(this.state.hover){
style.backgroundColor = "red"
} else {
style.backgroundColor = "blue"
}
return(
<Segment style={style} onMouseEnter={this.handleHover} onMouseLeave={this.handleExit} />
);
}
}
但是,即使它确实有效,我也会收到一条错误消息:
Warning:
div
was passed a style object that has previously been mutated. Mutatingstyle
is deprecated. Consider cloning it beforehand. Check therender
ofSegment
.
我从这个 post 中查找了答案,它说要这样实现:
const {styleFromProps} = this.props;
const newStyle = {...styleFromProps, marginTop: '45px'};
但是,我的样式是在类之外定义的,并且我没有从父组件向下传递任何样式。所以我不太确定如何将这个答案实现到我当前的代码中。
问题:
- 这个答案是实现悬停效果的最佳方式吗,还是我应该按照错误提示克隆组件?
- 我应该如何将答案应用到我当前的组件中?如有必要,可以更改结构。
最佳答案
只需使用 hover
状态来确定样式,而不是将其存储在单独的对象中。因为背景颜色取决于状态,所以不要将其存储在组件外部,使用三元运算符将其绑定(bind)到状态:
<Segment style={{
backgroundColor: this.state.hover ? 'red' : 'blue'
}} />
如果您有其他样式,只需使用扩展语法:
<Segment style={{
...styleObj,
backgroundColor: this.state.hover ? 'red' : 'blur'
}} />
这将复制您在 styleObj
中已有的所有样式,然后还应用背景色。您可以在 React JSX 中了解有关传播语法的更多信息 here .
关于javascript - 如何在不直接改变样式的情况下实现悬停效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45929798/