繁体   English   中英

如何在React Native打字稿中从父级调用子级组件方法

[英]How to call a child component method from parent in React Native typescript

你好,我是React Native的新打字员,在此示例代码中,我想从父类的parentCall函数中的子组件调用testChild函数,我不知道如何保持每个子组件的引用,我无法更改子组件代码我为每个子组件调用testChild吗?

class parent extends React.Component {
   public render(): JSX.Element {
        return (
         <child/>
         <child/>
               )
 public parentCall(): void{
   //call testChild for each Child component ??
}

}
class child extends React.Component {
 public render(): JSX.Element {
        return (
               <Text>Text</Text>
               )

 public testChild (): string{
   return Data ;
}

如果我对您的理解正确,则可以将每个<Child />组件存储在以下数组中: const children: JSX.Element[] = [Child, Child] render方法允许您传入要渲染的组件数组,因此,它的另一个好处是您现在有了一个可以循环使用并执行testChild的变量。

我解决了使用res和定义childRef字段的问题,并使用此代码将子组件的ref存储在childRef中

private onRef= (ref) => this.childRef= ref

并将其设置在子组件中

<child ref={this.onRef} />

现在使用childRef我可以调用其方法

childRef.testChild()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM