javascript - 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 做这样的事情?
解决方案
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 样式。
推荐阅读
- java - java.sql.SQLSyntaxErrorException:用户缺少权限或找不到对象:
- php - 强制 file_get_contents 或 stream_socket_client 使用所需的 dns 服务器
- java - 带有泛型参数接口的回调
- c - snprintf() 是否通过格式说明符使用根内存?
- android - Android 如何防止使用快速键盘?
- node.js - 通过 HTTPS 在 NodeJS 后端上的 Angular
- java - 如何在 JavaFx 中使表格视图的每个单元格可编辑
- jquery - JQuery Rails 更新属性不起作用
- python - 如何在 sqlalchemist Python 的 ORM 中构建这个 postgresql 查询?
- wordpress - Wordpress 联系表 7 标签不会被替换