使用React Refs触发命令性动画

时间:2018-07-07 13:15:51

标签: reactjs css-animations js-scrollintoview

从文档中可以看到Refs的用例:

Triggering imperative animations.

请问有人可以举个例子吗?使用Ref将其滚动到视图后,我试图将用户的注意力吸引到div上,我认为这可能是理想的用例,

1 个答案:

答案 0 :(得分:1)

有关更多信息,请参见Refs and the DOMEventTarget.addEventListener()Element.getBoundingClientRect()

function sortArray($a, $b) {
    $suma = array_sum($a['score']); // or array_max
    $sumb = array_sum($b['score']); // or array_max

    if ($suma == $sumb) { 
       return 0; 
    }
    return ($suma < $sumb) ? 1 : -1 ;
  // or just : return $suma <=> $sumb ; // As of PHP 7


usort($array, 'sortArray');
// 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'))