Как передать функцию с вложенных экранов

#reactjs #function #react-native #navigation #react-native-navigation

#reactjs #функция #react-native #навигация #реагировать-встроенная навигация

Вопрос:

У меня есть 2 вложенных экрана в navigator , и я хочу использовать функцию с одного из этих экранов на другой (от Screen1.js до Screen2.js ). Функция, которую я хочу вызвать, Screen2.js является addList() . Это Screen1.js

 export default function Screen1({navigation}){
   //...

  function addList (list){
   //Code...
   };

  //...
}
  

Я попытался импортировать функцию addList и использовать ее таким образом в Screen2 :

 import addList from './Screen1

//...

export default function Screen2({navigation}){
  //...

  function createSomething(){
    //...   
    addList(list);
    //...         
  }

  //...
}
  

Однако моя попытка оказалась неудачной. Как я могу выполнить это?

Ответ №1:

Список добавлений должен быть в родительском компоненте. Таким образом, вы можете передать функцию в качестве реквизита в screen1 и screen2.

Комментарии:

1. Вы имеете в виду, что функция addList должна быть вне функции Screen1? А затем передать требуемое состояние в качестве реквизита?

2. да, это мое решение без ссылок на использование. Но решение Ajmal Hasan тоже хорошо.

Ответ №2:

Если я сделаю то, что вы хотите, с Ajmal решением, я думаю, что это должно быть:

 import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react'

const { forwardRef, useRef, useImperativeHandle } = React;
    
    // We need to wrap component in `forwardRef` in order to gain
    // access to the ref object that is assigned using the `ref` prop.
    // This ref is passed as the second parameter to the function component.
    const Screen1 = forwardRef((props, ref) => {
    
      // The component instance will be extended
      // with whatever you return from the callback passed
      // as the second argument
      useImperativeHandle(ref, () => ({
    
        addList() {
          alert("getAlert from Child");
        }
    
      }));
    
      return <h1>Hi</h1>;
    });

    const Screen2 = (props) => {
      return (
       <div>
         ....
         <button onClick={(e) => props.screen1Ref.addlist(...)}>addList</button>
       </div>
      )
    }
    
    const Parent = () => {
      // In order to gain access to the child component instance,
      // you need to assign it to a `ref`, so we call `useRef()` to get one
      const screen1Ref = useRef();
    
      return (
        <div>
          <Screen1 ref={screen1Ref} />
          <Screen2 screen1Ref={screen1Ref} />
        </div>
      );
    };
    
    ReactDOM.render(
      <Parent />,
      document.getElementById('root')
    );
  

Теперь в screen2 вы можете вызвать props.screen1Ref.addList(…)