从文档中可以看到Refs的用例:
Triggering imperative animations.
请问有人可以举个例子吗?使用Ref将其滚动到视图后,我试图将用户的注意力吸引到div上,我认为这可能是理想的用例,
答案 0 :(得分:1)
有关更多信息,请参见Refs and the DOM
,EventTarget.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'))