使用 mobx 转发 ref

Fowarding a ref with mobx

我正在尝试使用 React 和 Mobx 构建一个自定义组件视频播放器,我需要钻取从主要组件到子组件的引用,但是当我在上使用 forwardRef 函数时收到错误消息作为观察者的组件。 错误消息是“baseComponent 不是函数” 这是代码:

// code for main component
const videoPlayer = () => {

const controlsRef = useRef<any>(null);

return (<div>
// video player screen code //
<VideoPlayerButtonCode ref={controlsRef} />
<div>)

}

// the code for the players component

interface IProps{
 controlsRef: any;
}

const VideoPlayerButtonCode: React.FC<IProps> = fowardRef({props from iprops}, controlsRef ) => {

return (<div>

<Button ref={controlsRef}>Button i want to get a ref for from main</Button>
<div>)

}

export default observer(VideoPlayerButtonCode)

那是代码的模糊抽象,但实现相同。 mobx 对 ref 的支持有什么帮助,或者有什么方法可以将 refrence 存储在 mobx 商店中?

您使用的 mobx-react 是什么版本?它应该适用于最新的 7.0.0 版本,但如果您使用 mobx-react-lite@3.0.0.

它似乎会失败

我已经用所有工作变体制作了 codesandbox:https://codesandbox.io/s/httpsWhosebugcomquestions64227496-75xdz?file=/src/App.js

例如与你作品相同的版本:

const ComponentWithForwardRef = React.forwardRef((props, ref) => {
  return <div ref={ref}>My Observer Component</div>;
});

const ObserverComponentWithForwardRef = observer(ComponentWithForwardRef);

observer HOC 还有一个 forwardRef 选项,但它目前仅适用于 mobx-react-lite,因此不适用于常规 mobx-react 包错误 https://github.com/mobxjs/mobx-react/issues/868

你可以这样使用它:

const MyObserverComponent = observer(
  (props, ref) => {
    return <div ref={ref}>My Observer Component</div>;
  },
  { forwardRef: true }
);

如果一切都失败了,您可以像这样为您的 ref 使用自定义道具:

<MyObserverComponentCustomRef innerRef={myRef} />

// ...

const MyObserverComponentCustomRef = observer((props) => {
  return <div ref={props.innerRef}>My Observer Component Inner Ref</div>;
});