【发布时间】:2019-03-08 09:57:46
【问题描述】:
我需要像 example 那样移动菜单项下划线。
使用 jQuery,我会简单地获取菜单项的左侧位置和宽度。然后在悬停时执行stop.animation。
我正在尝试用React 制作这样的动画。但我不知道该怎么做。经过谷歌研究,我发现了流行的动画反应运动库。但我找不到如何在悬停时触发动画的方法。
【问题讨论】:
标签: javascript reactjs animation react-motion
我需要像 example 那样移动菜单项下划线。
使用 jQuery,我会简单地获取菜单项的左侧位置和宽度。然后在悬停时执行stop.animation。
我正在尝试用React 制作这样的动画。但我不知道该怎么做。经过谷歌研究,我发现了流行的动画反应运动库。但我找不到如何在悬停时触发动画的方法。
【问题讨论】:
标签: javascript reactjs animation react-motion
你真的不必用 React 来做。如果您不介意框下方的下划线,可以使用box-shadow 来实现。它还允许您将其稍微模糊一下以获得更多样式。
.App {
width: 900px;
overflow: hidden;
position: relative;
padding-bottom: 20px;
}
.box {
width: 200px;
height: 200px;
background: #eee;
border: 1px solid #333;
float: left;
margin-right: 10px;
}
.box:hover {
box-shadow: 0 10px blue;
transition: box-shadow 0.3s;
}
<div class="App">
<span class="box"></span>
<span class="box"></span>
<span class="box"></span>
<span class="box"></span>
</div>
【讨论】:
render() 函数中。另外,根据经验,如果不用 JS 也能轻松搞定,那就不要在 JS 里搞。
onmouseenter 的用例,而不依赖于 CSS。例如,当 UI 中需要副作用时。因此,此答案并未涵盖这一点,因此在这种情况下不应支持 IMO。
onMouseEnter 以获取副作用,没有什么可以阻止您这样做,但是问题中没有提到这一点。我提供了 YAGNI 类型的响应。
您可以使用 css 过渡和下划线的绝对定位条纹来做到这一点。然后在元素悬停时更新条带的 left 属性。
class App extends React.Component {
constructor() {
super()
this.state = {
left: 0,
}
}
handleMouseEnter = (e) => {
this.setState({
left: e.target.getBoundingClientRect().x - 8,
});
}
render() {
return (
<div className="App">
<div className="box" onMouseEnter={this.handleMouseEnter} />
<div className="box" onMouseEnter={this.handleMouseEnter} />
<div className="box" onMouseEnter={this.handleMouseEnter} />
<div className="box" onMouseEnter={this.handleMouseEnter} />
<div className="stripe" style={{ left: this.state.left }}/>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
.App {
width: 900px;
overflow: hidden;
position: relative;
padding-bottom: 20px;
}
.box {
width: 200px;
height: 200px;
background: #eee;
border: 1px solid #333;
float: left;
margin-right: 10px;
}
.stripe {
width: 200px;
height: 10px;
background: blue;
position: absolute;
bottom: 0;
transition: left 0.3s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
这是codepen上的一个例子
【讨论】:
handleMouseEnter = (e) => { this.setState({ left: e.target.getBoundingClientRect().x - 8, width: e.target.offsetWidth }); } 中更新条带的宽度