我有一个组件,我在其中传递ref值。我需要在高阶组件中获得传递的ref值。以下是代码示例:HOC:包裹的组件
import React from "react";
import HOC from './hoc';
const MeasuredInput = () => {
const ref = React.createRef();
return (
<div>
<button ref={ref}>Click me!</button>
</div>
)
};
export default HOC(MeasuredInput);
高阶组件:
import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
function NewComponent(props) {
const { forwardedRef } = props;
return <OriginalComponent ref={forwardedRef} {...props} />;
}
return React.forwardRef((props, ref) => {
return <NewComponent {...props} forwardedRef={ref} />;
});
};
提前感谢
您需要在HOC中创建ref
并将其向下传递,而不是相反。数据向下流动,HOC正在包装组件。
import React from "react";
const HigherOrderFunction = (OriginalComponent) => {
return function(props) {
const ref = useRef();
return <OriginalComponent ref={ref} {...props} />
}
};
原始组件:
import React from "react";
import HOC from './hoc';
const MeasuredInput = React.forwardRef((props, ref) => {
return (
<div>
<button ref={ref}>Click me!</button>
</div>
)
});
export default HOC(MeasuredInput);