我想通过访问useRef.current来调用类上的函数,就像使用类组件和DOM对象一样。我知道关于DOM和类实例等的所有规则,这使得useRefs成为可能,但是如何调用myfunctioncomponent.method()呢?
沙箱显示了错误:
https://codesandbox.io/s/class-vs-function-useref-zjee5?file=/src/App.js
错误:
警告:不能给函数组件参考。访问此引用的尝试将失败。您是想使用React.forwardRef()吗?
代码:
export const App = () => {
let functionref = useRef(null);
let domref = useRef(null)
let classref = useRef(null);
useEffect(() => {
console.log(functionref); // fails :(
console.log(domref); // works!
console.log(classref); // works !
classref.current.callme(); // works!
classref.current.callme(); // fails!
}, []);
return (
<>
<ClassComponent ref={classref}/>
<div ref={domref}>This is a DOM node</div>
<FunctionComponent ref={functionref} />
</>
);
};
class ClassComponent extends React.Component {
callme() {
console.log("ClassComponent function called!");
}
render() {
return (
<p>This is a class component</p>
)
}
}
const FunctionComponent = () => {
const callme = () => {
console.log("function called!");
}
return (
<p>This is a function component</p>
)
}也许我是想过分扭曲规则,或者引入反模式(?)如果是这样的话,我非常感谢关于访问函数组件或其他组件中的函数和属性的正确方法的建议。
任何帮助都很感激。
发布于 2021-02-20 18:27:41
对于您想要做的事情,您需要使用一个forwardRef,以便将ref传递给functional,我在下面给出了一个示例片段。在类组件中,ref允许您访问类组件方法,但是当您使用未发生的反应性功能组件进行访问时。相反,你只需拿回裁判,就由你来决定裁判中会有什么。这就是为什么在下面的代码片段中,您需要添加ref.current = { callme },以便callme方法在被调用为functionref.current.callme()时可用。
const FunctionComponent = React.forwardRef((_props, ref) => {
const callme = () => {
console.log("function called!");
};
ref.current = { callme };
return <p>This is a function component</p>;
});这是一个那个密码箱
https://stackoverflow.com/questions/66294583
复制相似问题