在一个展示型网站一些 hover 的小效果简单又实用。
在 React 中对元素 / 组件添加 onMouseEnter
和 onMouseLeave
即可完成鼠标移入移出事件。
Code
import React, {Component} from 'react';
import './index.css';
class Management extends Component {
constructor(props) {
super(props)
this.state = {
bool: false
}
this.handleBoolean = this.handleBoolean.bind(this)
}
handleBoolean(bool) {
this.setState({ bool })
}
render() {
let arr = []
for (let i = 0; i < 5; i++) {
arr.push(<Show
bool={this.state.bool}
handleBoolean={this.handleBoolean}
key={i}
/>)
}
return (
<div>
<ul>
{arr}
</ul>
</div>
)
}
}
class Show extends Component {
constructor(props) {
super(props)
this.state = {
bool: false
}
this.handleEnter = this.handleEnter.bind(this)
this.handleOut = this.handleOut.bind(this)
}
handleEnter() {
this.props.handleBoolean(true)
this.setState({
bool: true
})
}
handleOut() {
this.setState({
bool: false
})
this.props.handleBoolean(false)
}
render() {
let style = {}
if (this.props.bool) {
style = {
backgroundColor: 'black',
transition: 'all 1s'
}
}
if (this.state.bool) {
style = {
backgroundColor : ''
}
}
return <li
className="Abc111"
style={style}
onMouseEnter={this.handleEnter}
onMouseLeave={this.handleOut}>
</li>
}
}
export default Management
需要注意的是,组件 Show
虽然只定义了一次,但是在父组件中循环渲染了。其实挂载在 dom
上的有 N 多(本例中有5个),他们之间的 state
是独立管理的,并不是互通的。