【问题标题】:How to implement a design with react-spring?如何使用 react-spring 实现设计?
【发布时间】:2019-04-18 05:37:59
【问题描述】:

在项目的 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 示例中,它们也直接在 Spring 组件中直接修改 opacitytrasform,这是我不想要的

他们的文档中给出的弹簧组件示例

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

【问题讨论】:

    标签: javascript css reactjs animation react-spring


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多