javascript - 如何使用 react-spring 实现设计?

标签 javascript css reactjs animation react-spring

在元素的 repo 中,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 = '&nbsp;<br>&nbsp;',
    text = '&nbsp;<br>&nbsp;',
    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 示例中,它们直接修改 opacitytrasform也直接使用 Spring 组件,这是我不想要的

在他们的文档中给出了 spring 组件示例

<Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
  {props => <div style={props}>hello</div>}
</Spring>

最佳答案

如果你有鼠标坐标,视差效果相对容易实现,这里有一个类似效果的例子:https://twitter.com/0xca0a/status/1058505720574959616

它使用钩子(Hook),但同样适用于普通 Spring 。尽管这甚至可能是一个很好的示例,因为它不会在非常快的 mousemove 上重新渲染组件。你不会在你的情况下使用旋转,我猜是翻译,但关键是,你收到 x/y 并使用它来将你的图像插入到位。

编辑: 我已经 fork 了这个例子,这个版本使用翻译:https://codesandbox.io/embed/r5x34869vq

关于javascript - 如何使用 react-spring 实现设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53314014/

相关文章:

javascript - 如何在抓取 Google Play 评论时避免被封禁?

javascript - 加载ajax时如何显示图像

JavaScript 正则表达式未验证

reactjs - 在 MUI 数据网格中插入新行时如何自动递增行 id?

javascript - 如果键已经存在,如何创建对象的json数组

javascript - 如何将我的图像淡入容器中?

javascript - 将 watchify 与 babelify 一起使用

javascript - Storybook StoryRouter 故事被标记为必需

javascript - JSON.解析 : unexpected character at line 1 column 1 of the JSON data in Firefox only

css - 调整图像类型单选按钮中的标签位置