Demo
组件里利用useRef
保存变化的callback
:
const Demo = (props) => {
const { callback } = props;
const [scroller, setScroller] = React.useState(null);
const scrollerCallback = React.useRef(callback);
const onScrollerClick = () => {
scroller.doSomething();
};
React.useEffect(() => {
scrollerCallback.current = callback;
}, [callback])
React.useEffect(() => {
setScroller(
new Scroller(() => {
scrollerCallback.current()
})
);
}, []);
return (
<div>
<button onClick={onScrollerClick}>scroller</button>
</div>
);
};
还有一点:组件Demo
里没必要使用state
保存scroller
值(因为看本Demo的用法更像是在使用成员变量):
const Demo = (props) => {
const {callback} = props;
const scroller = React.useRef(null);
const scrollerCallback = React.useRef(callback);
const onScrollerClick = () => {
scroller.current.doSomething();
};
React.useEffect(() => {
scrollerCallback.current = callback;
}, [callback])
React.useEffect(() => {
scroller.current =
new Scroller(() => {
scrollerCallback.current()
})
}, []);
return (
<div>
<button onClick={onScrollerClick}>scroller</button>
</div>
);
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…