简体   繁体   中英

Calling a function in functional component from a React component

Say I have a Child component which is a functional component and a function a():

export default function child({ ... }) {
 
   ...

   function a() {
      ...
   }

...

}

and say I also have a parent which is a React.Component and the parent of the child component:

class parent extends Component {

    constructor(props) {
       super(props);
       this.child= React.createRef();
    }
    
     render() {
         return(
              <child ref = {this.child}/>
         )
    }
}

I am trying to call function a() from the parent component. I am aware that this is against the recommended React structure, but is there a way to How can I accomplish so?

Thank you.

Your parent component won't be aware of the function a() as it is scoped to your child (functional) component.

A different way to handle this, assuming you're only dealing with this single parent/child structure, would be to declare your function a() in the parent, then pass it to the child.

If the function is something that is likely needed in multiple, unrelated components, then exporting the function separately as a 'helper' function would allow it to be imported and used in different places.

Create the a function outside the child function.

export function a() {
  ...
}

export default function child({ ... }) {
  a();
  ...
}

This way you can call a function inside the child function and you can also import it in some other component.
Btw. React components should start with capital letter → function Child({...})

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