简体   繁体   中英

React createRef for a childComponent inside a ViewPager in React Native

I have created a signup module with three steps in my react native application where I have put all of the fields in the state of the parent component, and that gave me a very overloaded JSX file, So I am trying to move all of the fields validation functions to the related step and catch the returned value 'valid/ not valid' in the parent screen so I can move to the next step by clicking on the next button which will navigate to the next viewpager page.

So I have tried to use the React.createRef to reference the child step in the parent and call the methods within the child in the future:

SignupScreen.jsx (Parent):

constructor(props) {
    super(props);

    this.state = {
    ...fields,
    }
    this.signupStepOneRef = React.createRef();
  }
  render(){
  return (  
          <ViewPager
            initialPage={0}
            style={styles.fieldsContainer}
            scrollEnabled={false}
            ref={(vp) => (this.viewPager = vp)}
          >
                <SignupStepOne
                  fieldsContainerStyle={styles.fieldsContainer}
                  scrollViewStyle={styles.scrollView}
                  key="1"
                  onInputChanged={this.handleChange}
                  stepOneErrors={this.state.stepOneErrors}
                  ref={this.signupStepOneRef}
                />
                ...OtherSteps
         </ViewPage>
) 
     }

But this code gives me an Object: {current: null} when I console.log(this.signupStepOneRef). The official documentation says that this won't work if the child is a function, but changing it to a class component didn't help either. I have also tried the:

ref={(obj) => this.signupStepOneRef = obj}

syntax but also gives me the same null current object.

I finally found a solution, since viewpager children cannot be referenced directly I have wrapped up the child page in a View component and that solved my issue. The solution code:

        <ViewPager
        initialPage={0}
        style={styles.fieldsContainer}
        scrollEnabled={false}
        ref={(vp) => (this.viewPager = vp)}
        >
            <View key="1">
            <SignupStepOne
              fieldsContainerStyle={styles.fieldsContainer}
              scrollViewStyle={styles.scrollView}         
              onInputChanged={this.handleChange}
              stepOneErrors={this.state.stepOneErrors}
              ref={this.signupStepOneRef}
            />
            </View>
            ...OtherSteps
     </ViewPage>

The key attribute needs to be moved to the wrapper view.

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