Let <Word />
be a simple functional component (without state) which takes a few props and displays a word.
<Word group={1} />
<Word group={2} />
<Word group={2} />
<Word group={1} />
<Word group={2} /> //There might be many more groups etc.
on hover of one of these <Words />
, I'd like to highlight (change background-color to yellow or something) all of the words in the same group. Not just the word hovered, but that word + all the words in the same group.
I wanted to do this with CSS-only originally, but that is apparently not possible. How could I do something like this with React in a minimal fashion?
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;
Implement highLight css style as you desired.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.