admin管理员组文章数量:1397102
I'm developing a React Native app with Hooks. (No Classes). When we use classes, we can create a ref to a child ponent like this.
<Child ref={ponent => this.childComponent = ponent} />
But, how to do this when we use Hooks?
I want something like this.
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?
)
}
I hope you understand what I'm trying to say.
I'm developing a React Native app with Hooks. (No Classes). When we use classes, we can create a ref to a child ponent like this.
<Child ref={ponent => this.childComponent = ponent} />
But, how to do this when we use Hooks?
I want something like this.
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?
)
}
I hope you understand what I'm trying to say.
Share Improve this question asked Apr 27, 2020 at 11:29 Sennen RandikaSennen Randika 1,6463 gold badges17 silver badges35 bronze badges1 Answer
Reset to default 7In order to define refs with hooks, you need to use useRef
hook. And in order to apply ref to functional ponents you need to use forwardRef
and 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} />
)
}
本文标签: javascriptHow to uses refs in React Native with HooksStack Overflow
版权声明:本文标题:javascript - How to uses refs in React Native with Hooks? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744137654a2592472.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论