[英]React HOC: Pass data attributes to the first child/element of wrapped component
[英]React Native pass ref to functional component that is wrapped with a HOC
我正在嘗試將父級的 ref 傳遞給它的子級。 孩子是一個功能組件,所以我在做:
// 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;
任何想法如何將引用傳遞給包裝在 HOC 上的功能組件?
我試圖做這樣的事情:
const Configuration = forwardRef((props, ref) => withFirebase(() => {
const { colors } = useTheme();
const fall = useRef(new Animated.Value(1)).current;
return <></>
}));
export default Configuration;
但沒有用。 謝謝你。
傳遞帶有功能組件的 props 的唯一方法是使用 React.forwardRef()。 但是,如果您正在使用它,為什么會出現錯誤(我想是“功能組件不接受 refs)?
如果您不將組件包裝在 HOC 中,一切都會很好地工作,所以問題出在您的 HOC 上。
const withFirebase = (Component) => (props) => (
<FirebaseContext.Consumer>
{(firebase) => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
HOC 只是另一個組件,它接收“WrappedComponent”以概括應用程序中的常見情況。 您已將其實現為功能組件,因此您可以完美地使用 React.forwardRef 使其接收引用。
像這樣:
const withFirebase = (Component) => React.forwardRef((props, ref) => (
<FirebaseContext.Consumer>
{(firebase) => <Component ref={ref} {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
));
但也許,您正在不希望使用 refs 的組件中使用您的 HOC……在這種情況下,不要更改您的 HOC,只需將 ref 作為道具傳遞給功能組件。 像這樣:
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 作為值。
就這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.