我正在用Hooks开发一个React Native应用程序。(无班)。当使用类时,我们可以像这样创建对子组件的引用。
<Child ref={component => this.childComponent = component} />
但是,当我们使用钩子时该怎么做?
我想要这样的东西。
export default function Child() {
const foo = () => {
//do something
}
return(
//something
)
}
export default function Parent() {
const myFunc = () => {
ref.foo();
}
return(
<Child ref={.........} /> //This is what I want to know how to do?
)
}
希望您能理解我的意思。
为了使用钩子定义引用,您需要使用useRef
钩子。而为了参考适用于功能组件,您需要使用forwardRef
和useImperativeHandle hook
function Child(props, ref) {
const foo = () => {
//do something
}
useImperativeHandle(ref, () => ({
foo
}));
return(
//something
)
}
export default React.forwardRef(Child)
export default function Parent() {
const childRef = useRef(null)
const myFunc = () => {
childRef.current.foo();
}
return(
<Child ref={childRef} />
)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句