【问题标题】:Triggering imperative animations using React Refs使用 React Refs 触发命令式动画
【发布时间】:2022-01-25 15:05:48
【问题描述】:

在文档中,有一个 Refs 用例:

Triggering imperative animations.

有人可以举个例子来说明应该如何做到这一点吗?在使用 Ref 将其滚动到视图后,我试图将用户的注意力吸引到 div 上,我认为这可能是一个理想的用例?

【问题讨论】:

    标签: reactjs css-animations js-scrollintoview


    【解决方案1】:

    有关详细信息,请参阅 Refs and the DOMEventTarget.addEventListener()Element.getBoundingClientRect()

    // Imperative Animation
    class ImperativeAnimation extends React.Component {
    
      // State.
      state = {background: '#fff'}
    
      // Render.
      render = () => (
        <div ref={this.divRef} style={{height: '200vh', background: this.state.background}}>
          Scroll to turn background papayawhip.
        </div>
      )
      
      // Did Mount.
      componentDidMount() {
        window.addEventListener('scroll', this.onScroll)
      }
      
      // Div Ref.
      divRef = React.createRef()
      
      // On Scroll
      onScroll = event => {
        const div = this.divRef.current
        const {y} = div.getBoundingClientRect()
        if (y <= 0) this.setState({background: 'papayawhip'})
        else this.setState({background: '#fff'})
      }
      
    }
    
    // Mount.
    ReactDOM.render(<ImperativeAnimation/>, document.querySelector('#root'))
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <div id="root"></div>

    【讨论】:

      【解决方案2】:

      我认为命令式动画意味着通过javascript定义动画

      https://anvaka.github.io/sj/compare/

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2020-09-29
      • 2020-01-14
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多