在项目的仓库中,react-redux应用程序使用JS文件中的CSS进行设置。现在,就像该网站一样,我应该使用鼠标悬停为图片设置动画:https://www.madwell.com/
该组件最初是一个功能组件,我将其更改为基于类的组件,如下所示:
```
class BannerContainer extends React.Component{
constructor(props){
super(props);
this.state = {
x: 0,
y: 0
};
this.handleMouseMove = this.handleMouseMove.bind(this);
}
componentDidMount(){
window.addEventListener("mousemove", this.handleMouseMove);
}
componentWillUnmount(){
window.removeEventListener('mousemove', this.handleMouseMove);
}
handleMouseMove({ x, y }){
this.setState({
x : x / window.innerWidth,
y : y / window.innerHeight
})
}
render(){
const { banner = {} } = this.props;
const {
title = ' <br> ',
text = ' <br> ',
image__google_350x80 = '',
image__app_350x80 = '',
image__bg1_1166x1878 = '',
image__bg2_961x1782 = '',
image__curve_730x151 = ''
} = banner;
return (
<Container>
<BGPatch>
{console.log(this.state.x , this.state.y)}
<img src={'/images/bg_purple.jpg'} alt="" />
</BGPatch>
```
在此示例中,我能够监听mouse-move
事件并相应地获取x和y坐标。但是现在我必须使用react-spring
库来实现它,那我该怎么做?同样,对于每个组件,CSS也应该用单独的JS文件编写,就像在react-spring
示例中那样,它们直接在Spring组件中直接修改opacity
或trasform
,这也是我要做的。想要
文档中给出的spring组件示例
<Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
{props => <div style={props}>hello</div>}
</Spring>
答案 0 :(得分:1)
如果您具有鼠标坐标,则视差效果相对容易实现,下面是一个具有类似效果的示例:https://twitter.com/0xca0a/status/1058505720574959616
它使用钩子,但是同样的事情也适用于常规弹簧。尽管这甚至可能是一个很好的示例,因为它不会在mousemove上重新渲染组件,这非常快。我猜您不会使用旋转,我会翻译,但是重点是,您会收到x / y并使用它将图像插值到位置。
编辑: 我已经分叉了示例,该版本使用了以下翻译:https://codesandbox.io/embed/r5x34869vq