让<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做这样的事情?
答案 0 :(得分:1)
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样式。