React Navigation - How to pass data across different screens in TabNavigator?

后端 未结 5 1946
野的像风
野的像风 2021-01-14 06:17

I have a TabNavigator, and in each tab is a StackNavigator. Inside the StackNavigator, I have screens. The screens in each Tab do not call each other directly; the TabNaviga

5条回答
  •  北海茫月
    2021-01-14 06:57

    I came across a similar problem. I had a multi page form that the client insisted on having each step be enclosed in a tab on a tab bar. I used the react navigation createMaterialTopTabNavigator to create the navigator and couldn't find an easy way to pass the form data between tabs.

    What I end up doing was using react's Context API and wrapped the tab navigator in a root form container that provides the context value to the navigator and routes inside. Here is how I did it:

    Root form container

    // MultiScreenForm.js
    imports...
    import MultiScreenFormNavigator from './MultiScreenFormNavigator'
    
    export const FormContext = React.createContext()
    
    class MultiScreenForm extends Component {
      constructor(props) {
        super(props)
        this.state = {
          // formDataHere
          formUpdaters: {
               onToggleOptIn: this.handleToggleOptIn // example updater method
               // other
            }
          }
       }
        handleToggleOptIn = () => {
        // toggle opt in form data with this.setState
      }
    
      render() {
        return (
          
            
          
        )
      }
    }
    
    export default MultiScreenForm
    

    Example form page

    // ProfileForm.js
    imports...
    import { FormContext } from './MultiScreenForm'
    
    class ProfileForm extends Component {
      render() {
        // FormContext.Consumer uses function as child pattern
        return (
          
            { (context) => (
                 // our form can now use anything that we pass through the context
                 // earlier, we passed the root form's state including an updater
                 

    Tab navigator

    // MultiScreenFormNavigator.js
    imports...
    import ProfileForm from './ProfileForm'
    import { createMaterialTopTabNavigator } from 'react-navigation'
    
    const MultiScreenFormNavigator = createMaterialTopTabNavigator(
      {
        Profile: ProfileForm,
        // AnotherForm: AnotherForm
      },
      // { navigator options here... }
    )
    
    export default MultiScreenFormNavigator
    

    We then render the MultiScreenForm instead of the tab navigator directly.

    This worked for me but I feel there should be an easier way to do this. I hope people who read this can share their approaches.

提交回复
热议问题