使用依赖于ref不为null的react钩子

时间:2019-10-24 18:42:13

标签: javascript reactjs rxjs react-hooks

我正在尝试将observable传递到react-jss中,以随着可观察对象发出新值来更改样式。像这样开箱即用:

function randomColor() { ... } // generates a random color

const App = () => {
  const source = timer(0, 1000).pipe(map(randomColor));
  const useStyles = createUseStyles({bg: {background: source}});
  const classes = useStyles();
  return (<div className={classes.bg}>test</div>);
}

当我想使用本地鼠标事件中的可观察对象时,问题就来了,在我的情况下,我正在复制拖放功能。在这种情况下,我的组件看起来像这样

function createDraggable(el) { ... } // => Observable<{x: number, y: number}>
const App = () => {
  const div = useRef(null);
  const useStyles = createUseStyles({
    div: { 
      left: createDraggable(div).map(coords => coords.x ), 
      top: createDraggable(div).map(coords => coords.y) 
    }
  })
  useStyles(); // error null is not an HTMLElement
  return(...) 
}

为确保ref不为空,我需要在createDraggable内调用useEffect,但是我不能使用useStyles。我只想出一个可能的解决方案,即放弃本机dom事件,并结合使用Subjectsynthetic events来复制行为而无需引用。我不知道这是否是最好的方法。似乎有很多重新发明了轮子。

0 个答案:

没有答案