简体   繁体   English

React:将鼠标悬停在组件1上,更改另一个组件的样式

[英]React: on hover over component 1, change the style of another component

I am learning react and I have some code which waits for a hover over a button and then applies an opaque white overlay over the image over which you hover (and this works): 我正在学习反应,我有一些代码等待悬停在按钮上,然后在你悬停的图像上应用不透明的白色覆盖(这样可行):

class Product extends Component {
  constructor(props) {
        super(props);
        // 1. bind your functions in the constructor.
        this.mouseOver = this.mouseOver.bind(this);
        this.mouseOut = this.mouseOut.bind(this);
        this.state = {
            hover: false
        };
    }

    // 2. bind it with fat arrows.
    mouseOver = () => {
        this.setState({hover: true});
    }
    mouseOut() {
        this.setState({hover: false});
    }

  render() {
    return (
      <Link to={"/products/"+this.props.value.uid}>
        <button className="Product" onMouseEnter={this.mouseOver.bind(this)} onMouseLeave={this.mouseOut.bind(this)}>
          <img className="ImageGrid" src={this.props.value.media}/>
          {this.state.hover ? (
            <div className="ImageOverlay"> 
              <div className="TextOverlay">
                <p><b>{this.props.value.name}</b></p>
                <p>${this.props.value.price}</p>
              </div>
            </div>) : null}  
        </button>
      </Link>
    );
  }
}

My question is... let's say that instead of adding an overlay over the image rendered by this component, I wanted to change an image rendered by another component and not by applying an overlay div, but by changing some CSS setting of said image, like applying a filter: filter: grayscale(100%). 我的问题是......让我们说,不是在这个组件渲染的图像上添加叠加,我想改变由另一个组件渲染的图像,而不是通过应用叠加div,而是通过改变所述图像的一些CSS设置,比如应用滤镜:滤镜:灰度(100%)。 So there is this image: 所以有这个图像:

<img className="PicBox" src={this.state.img[sid-1]} />

Rendered by another component. 由另一个组件呈现。

Here is what I am thinking the strategy might be: 以下是我认为策略可能是:

Have my original component (the one over which I hover), have a prop "state" which keeps track on whether or not i hover over it, like I did above. 让我的原始组件(我悬停的组件)有一个道具“状态”,它跟踪我是否将鼠标悬停在它上面,就像我上面所做的那样。

In the other component which renders ImageX, I need to somehow access the prop of the Hover component, and check its state, to decide how to render the image (with grayscale or not). 在呈现ImageX的另一个组件中,我需要以某种方式访问​​Hover组件的prop,并检查其状态,以决定如何呈现图像(具有灰度或不灰度)。

How do I access state of the hover component within another component? 如何在另一个组件中访问悬停组件的状态?

(Or if my strategy is off, a hint would be appreciated) (或者,如果我的策略是关闭的,那么我们将不胜感激)

As long as you don't use some state managing library such as redux or flux and you want to access state between components, you need a common parent between those. 只要您不使用某些状态管理库(如redux或flux)并且您希望访问组件之间的状态,就需要在这些库之间使用公共父级。 In the end you have something like this (pseudocode): 最后你有这样的东西(伪代码):

ParentComponent {
   hoverHandler(isHover) {
       this.childIsHover = isHover;
   }
   render() {
        <hoverComponent onHover={this.hoverHandler} />
        <imageComponent overlay={this.childIsHover} />
   }
}

When working with React, you've got to think about who should have the responsibility of maintaining state. 在与React合作时,您必须考虑谁应该负责维护状态。 So in this case, the state should not be stored in the button component, because it needs to be accessed by another component which is not one of its children. 所以在这种情况下,国家应该被存放在按钮组件,因为它需要由其他组分,它是不是它的一个子访问。

Instead, you should create a parent component that is responsible for storing the hover state, and also renders both the button and image components. 相反,您应该创建一个负责存储悬停状态的父组件,并同时渲染按钮和图像组件。 You can bind functions to the parent, so that when they are passed as props to other children, they can still update the state of the parent. 您可以将函数绑定到父级,这样当它们作为props传递给其他子级时,它们仍然可以更新父级的状态。

So for example, your parent component might look like this: 例如,您的父组件可能如下所示:

class Parent extends Component {
  constructor () {
    super()

    this.state = {
      hover: false
    }

    this.updateHoverState = this.updateHoverState.bind(this)
  }

  updateHoverState (hover) {
    this.setState({ hover: hover })
  }

  render () {
    <div>
      <ButtonComponent updateHoverState={this.updateHoverState} />
      <ImageComponent hover={this.state.hover} />
    </div>
  }
}

Now, your button component can just be a function, and does not need to maintain any state of its own. 现在,您的按钮组件可以只是一个函数,而不需要维护它自己的任何状态。 You can update the parent state by calling this.props.updateHoverState : 您可以通过调用this.props.updateHoverState来更新父状态:

function ButtonComponent (props) {
  return (
    <button
      onMouseEnter={() => this.props.updateHoverState(true)}
      onMouseLeave={() => this.props.updateHoverState(false)}
    />
  )
}

In React, you generally pass properties down to children components. 在React中,通常将属性传递给子组件。 So rather than trying to "reach up and over" into an unrelated component to access it's state, you should be accessing a state that's been passed down to your from a shared parent component. 因此,您应该访问从共享父组件传递给您的状态,而不是尝试“伸手可及”到一个不相关的组件来访问它的状态。

So if the ImageX component is a child of Product, you can pass the state directly into it <ImageX hover={this.state.hover} /> . 因此,如果ImageX组件是Product的子项,则可以将状态直接传递给它<ImageX hover={this.state.hover} /> You can then access hover in the ImageX props. 然后,您可以在ImageX道具中访问hover

If it's not a child of Product, you'll want to pass down the state from a shared parent and access it from both components. 如果它不是Product的子级,您将希望从共享父级传递状态并从两个组件访问它。

You can use Context and make a theme-like color set for your components. 您可以使用Context并为组件制作类似主题的颜色集。 Read about the context in the docs and codeburst . 阅读docscodeburst中的上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM