简体   繁体   中英

Calling a callback function from different component onPress in different Component React Native JS

I want the ability to call a function in a third party callback function from say a button with onPress function

<button onPress={this.componentX.onCalendarToggled} /> 

<componentX onCalendarToggled={(calendarView) => { console.log(calendarView); }} />

I just want to trigger the callback function from a different component. I'm new to JS and react native

It's not easy, especially if you are new to React but it can be done with forwardRef and useImperativeHandle .

You need to wrap the subject component with React.forwardRef and decalre 'useImperativeHandle' like this:

    const Component = React.forwardRef((props, ref) => {
     
     ...

     useImperativeHandle(ref, () => ({
          someFunction() {
              doSomething()
          }
      }));

     ...
      
     return {
          ...
     }
 }) 

Then on some other component you can call it like this:

const someRef = useRef();

const fireFunction = () => {
     someRef.someFunction()
}

return (
     <Component ref={someRef} />
)

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