从文档中,Refs 有这个用例:
Triggering imperative animations.
有人可以举例说明应该如何做到这一点吗?在使用 Ref 将其滚动到视图中后,我试图将用户的注意力吸引到div 上,我认为这将是一个理想的用例,也许?
有关详细信息,请参阅Refs and the DOM
、EventTarget.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>
我认为命令式动画意味着通过javascript定义动画
https://anvaka.github.io/sj/compare/