5

从文档中,有一个 Refs 的用例:

Triggering imperative animations.

有人可以提供一个应该如何完成的例子吗?在使用 Ref 将其滚动到视图后,我试图将用户的注意力吸引到 div 上,我认为这可能是一个理想的用例,也许?

4

2 回答 2

5

有关详细信息,请参阅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>

于 2018-07-07T14:00:19.913 回答
0

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

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

于 2022-01-25T07:05:48.697 回答