简体   繁体   中英

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

hello i'm new in React Native with typescript and in this example code i want to call testChild function from child Component in parentCall function in parent class and i dont know how to keep reference of each child component i cant change child component code how can i call testChild for each child component ?

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 ;
}

If I understand you correctly, you can store each <Child /> component in an array like: const children: JSX.Element[] = [Child, Child] . The render method allows you to pass in arrays of components for rendering, so the added bonus of this is you now have a variable you can loop over and execute testChild with.

i solve my problem with Using res and define childRef field and with this code i store ref of child component in childRef

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

and set it in child component

<child ref={this.onRef} />

now with childRef i can call its methods

childRef.testChild()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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