【问题标题】:React Native pass ref to functional component that is wrapped with a HOCReact Native 将 ref 传递给用 HOC 包装的功能组件
【发布时间】:2020-08-25 20:59:02
【问题描述】:

我正在尝试将 ref 从父级传递给其子级。 child是一个函数组件,所以我在做:

// Child
const Configuration = forwardRef((props, ref) => {
    const { colors } = useTheme();

    const fall = useRef(new Animated.Value(1)).current;

    return <></>
});

一切运行良好。但是当我尝试这样做时

export default withFirebase(Configuration);

问题出现了……

这里是 HOC 组件:

import React from "react";

import { FirebaseContext } from "../Firebase/";

const withFirebase = (Component) => (props) => (
  <FirebaseContext.Consumer>
    {(firebase) => <Component {...props} firebase={firebase} />}
  </FirebaseContext.Consumer>
);

export default withFirebase;

任何想法如何将 ref 传递给包装在 HOC 上的功能组件?

我尝试过这样做:

const Configuration = forwardRef((props, ref) => withFirebase(() => {
    const { colors } = useTheme();

    const fall = useRef(new Animated.Value(1)).current;

    return <></>
}));

export default Configuration;

但是没有用。谢谢。

【问题讨论】:

    标签: javascript reactjs react-native expo


    【解决方案1】:

    使用函数式组件传递 props 的唯一方法是使用 React.forwardRef()。但是,如果您使用它,为什么会出现错误(我想是“功能组件不接受引用)?

    如果您不将组件包装在 HOC 中,一切都会很好,所以问题出在您的 HOC 上。

    const withFirebase = (Component) => (props) => (
      <FirebaseContext.Consumer>
        {(firebase) => <Component {...props} firebase={firebase} />}
      </FirebaseContext.Consumer>
    );
    

    HOC 只是另一个组件,它接收“WrappedComponent”以概括应用中的常见情况。您已经将它实现为一个功能组件,因此您可以完美地使用 React.forwardRef 使其接收 refs。

    就像这样:

    const withFirebase = (Component) => React.forwardRef((props, ref) => (
      <FirebaseContext.Consumer>
        {(firebase) => <Component ref={ref} {...props} firebase={firebase} />}
      </FirebaseContext.Consumer>
    ));
    

    但也许,您在不希望使用 refs 的组件中使用您的 HOC...在这种情况下,不要更改您的 HOC,只需将 ref 作为 props 传递给功能组件。像这样:

    const Configuration = withFirebase(function Configuration(props) {
      const { colors } = useTheme();
    
      const { inputRef } = props;
    
      const fall = useRef(new Animated.Value(1)).current;
    
      return <></>;
    });
    
    
    export default forwardRef((props, ref) => ( // <----- The magic
      <Configuration {...props} inputRef={ref} />
    ));
    

    当您将 ref 作为道具传递时,您不能这样做:

    export default forwardRef((props, ref) => ( // <----- The magic
      <Configuration {...props} ref={ref} />
    ));
    

    因为属性“ref”是 React 保留的,并且只会期望 refs 作为值。

    就是这样。

    【讨论】:

    • Pd:最后一个解决方案与您上一次尝试“相似”。您不是先将组件包装在 React.forwardRef 中,然后再包装在 HOC 中,而是先将其包装在 HOC(只需要 props)中,然后再包装在 React.forwardRef 中,将 ref 作为 props 传递给 HOC。
    猜你喜欢
    • 2018-02-03
    • 2020-08-09
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多