首页 > 解决方案 > React/Redux:悬停一个组件时,更改所有组件的颜色

问题描述

让我们<Word />成为一个简单的功能组件(没有状态),它需要一些道具并显示一个单词。

<Word group={1} />
<Word group={2} />
<Word group={2} />
<Word group={1} />
<Word group={2} /> //There might be many more groups etc.

在其中一个悬停时<Words />,我想突出显示(将背景颜色更改为黄色或其他)同一组中的所有单词。不只是这个词悬停,而是那个词+同一组中的所有词。

我最初只想使用 CSS 来做到这一点,但这显然是不可能的。我怎么能以最小的方式用 React 做这样的事情?

标签: javascriptreactjsreact-nativereact-reduxflux

解决方案


import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor(props){
    super(props);
        this.state = {
        currentSelectedGroup: 0,
        value: 0
        };
    this.hoverOff = this.hoverOff.bind(this);
    this.hoverOn = this.hoverOn.bind(this);
    }

    hoverOn(selectedGroup){
    this.setState({
      currentSelectedGroup: selectedGroup
    });
    }

    hoverOff(){
    this.setState({ currentSelectedGroup: 0 });
    }

    render(){
    return(
    <div>
         <Word group={2}
      currentSelectedGroup={this.state.currentSelectedGroup}
      onMouseEnter={ ( ) => this.hoverOn(2) }
      onMouseLeave = {this.hoverOff} />
   <Word group={1}
      currentSelectedGroup={this.state.currentSelectedGroup}
      onMouseEnter={ ( ) => this.hoverOn(1) }
      onMouseLeave = {this.hoverOff}
       />
        <Word group={1}
      currentSelectedGroup={this.state.currentSelectedGroup}
      onMouseEnter={ ( ) => this.hoverOn(1) }
      onMouseLeave = {this.hoverOff}
       />

    <Word group={2}
      currentSelectedGroup={this.state.currentSelectedGroup}
      onMouseEnter={ ( ) => this.hoverOn(2) }
      onMouseLeave = {this.hoverOff} />
      </div>
      )
    }
}

const Word = (props) => {
  let wordClassName =  props.group == props.currentSelectedGroup  ? 'highLight':'default';
  return (
      <div className={`${wordClassName}`}
          onMouseEnter={ props.onMouseEnter }
              onMouseLeave = {props.onMouseLeave}>
      This is my Word Group : {props.group}
      </div>);

  }

export default App;

根据需要实现 highLight css 样式。


推荐阅读