infeng / react-viewer

react image viewer, supports rotation, scale, zoom and so on
https://infeng.github.io/react-viewer
MIT License
734 stars 137 forks source link

不支持获取ref,默认创建div无法删除,无法函数调用 #158

Open Binote opened 2 years ago

Binote commented 2 years ago
- export default (props: ViewerProps) => {
+ export default React.forwardRef((props: ViewerProps, ref) => {
  const defaultContainer = React.useRef(typeof document !== 'undefined' ? document.createElement('div') : null);
  const [ container, setContainer ] = React.useState(props.container);
  const [ init, setInit ] = React.useState(false);

  React.useEffect(() => {
+    if(!container){
       document.body.appendChild(defaultContainer.current);
+    }
  }, []);

  React.useEffect(() => {
    if (props.visible && !init) {
      setInit(true);
    }
  }, [props.visible, init]);

  React.useEffect(() => {
    if (props.container) {
      setContainer(props.container);
    } else {
      setContainer(defaultContainer.current);
    }
  }, [props.container]);

  if (!init) {
    return null;
  }
  return ReactDOM.createPortal((
    <ViewerCore
+      // 其他组件也需要用`React.forwardRef`来支持ref
+      ref={ref}
      {...props}
    />
  ), container);
});