Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在不直接改变样式的情况下实现悬停效果?_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript 如何在不直接改变样式的情况下实现悬停效果?

Javascript 如何在不直接改变样式的情况下实现悬停效果?,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个React组件,它实现了悬停效果,例如: let style = { backgroundColor: "blue" } class someComponent extends React.Component{ constructor(props){ super(props) this.state = { hover: false } } handleHover(event) { this.setState({ hove

我有一个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} />
    );
  }
}
但是,我的样式是在类之外定义的,我不会从父组件传递任何样式。所以我不太确定如何在我当前的代码中实现这个答案

问题:

  • 这是实现悬停效果的最佳方法,还是应该像错误建议的那样克隆组件
  • 我应该如何在当前组件中实现答案?如有必要,可改变结构

只需使用
悬停
状态来确定样式,而不是将其存储在单独的对象中。因为背景颜色取决于状态,所以不要将其存储在组件外部,使用三元运算符将其绑定到状态:

<Segment style={{
  backgroundColor: this.state.hover ? 'red' : 'blue'
}} />

如果您有其他样式,只需使用扩展语法:

<Segment style={{
  ...styleObj,
  backgroundColor: this.state.hover ? 'red' : 'blur'
}} />


这将复制
styleObj
中已有的所有样式,然后应用背景色。您可以在React JSX中了解有关spread语法的更多信息。

如果有任何混淆,我从构造函数中排除了句柄函数的.bind(this)语句。为了这篇文章,我没有在这个对象中包含所有需要的样式。因此,如果有必要使用样式对象,我将如何实现它?“我的样式”对象的样式不仅仅是背景色change@PhillipR编辑。
<Segment style={{
  ...styleObj,
  backgroundColor: this.state.hover ? 'red' : 'blur'
}} />