使用 mobx 转发 ref

DBa*_*nkx 2 javascript reactjs mobx mobx-react-lite

我正在尝试使用 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)

Run Code Online (Sandbox Code Playgroud)

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

Dan*_*ila 6

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

我现在已经用所有工作变体制作了代码和盒子:https ://codesandbox.io/s/httpsstackoverflowcomquestions64227496-75xdz?file=/src/App.js

例如与您的工作相同的版本:

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

const ObserverComponentWithForwardRef = observer(ComponentWithForwardRef);
Run Code Online (Sandbox Code Playgroud)

HOC也有一个forwardRef选项observer,但它目前仅适用于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 }
);
Run Code Online (Sandbox Code Playgroud)

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

<MyObserverComponentCustomRef innerRef={myRef} />

// ...

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