如何在React Native中调用子组件函数?

时间:2020-06-09 11:43:27

标签: javascript reactjs react-native

我想从同级组件中调用组件函数,因此决定使用父组件和refs进行调用。 这是我的父组件 SMS-Registration.js

import React, {Component} from 'react';

import PhoneNumber from './Sms/PhoneNumber';
import VerificationCode from './Sms/VerificationCode';

class SmsRegistration extends Component {
  state = {
    confirm: false,
    phone: '',
    content: null,
  };

  setToTrue = () => {
    this.setState({
      confirm: true,
    });
  };

  resendCode = () => {
    this.child.testFunc();
  };

  render() {
    return (
      <>
        {!this.state.confirm ? (
          <PhoneNumber
            onRef={ref => (this.child = ref)}
            setToTrue={this.setToTrue}
          />
        ) : (
          <VerificationCode
            resend={this.resendCode}
          />
        )}
      </>
    );
  }
}

export default SmsRegistration;

第一个子组件 PhoneNumber.js

import React, {Component} from 'react';
import {View} from 'react-native';
import {ButtonComponent} from 'components/common';


export default class PhoneNumber extends Component {


  testFunc = () => {
    console.log('test func click');
  };

  setToTrue = () => {
    this.props.setToTrue();
  };

  render() {
    return (
      <View>
        // this is custom button component which receives 2 params (title, callback)
        <ButtonComponent
                buttonCaption="Set to True"
                onTouch={this.setToTrue}
              />
      </View>
    );
  }
}

和第二个子组件 Verification.js

import React, {Component} from 'react';
import {View} from 'react-native';
import {ButtonComponent} from 'components/common';

export default class VerificationCode extends Component {
  constructor(props) {
    super(props);
  }

  resendCode = () => {
    this.props.resend();
  };


  render() {
    const changeValue = (value) => {
      this.getData(value);
    };
    return (
      <View>
        <ButtonComponent
            buttonCaption="Resend Code"
            onTouch={this.resendCode}
        />
      </View>
    );
  }
}

当我尝试从 PhoneNumber.js 运行方法时,它说this.child未定义。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我认为是因为PhoneNumber组件尚未初始化。由于您有条件,因此请确认状态为PhoneNumber组件和this.child,直到它变为true为止。这就是为什么您收到未定义的错误的原因。